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.

feat(cohorts): disambiguate rust routing predicate (#77881)

Matheus Batista1e341a037c41
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 96af2a3af85e..c787bb4d812a 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
@@ -26,6 +26,7 @@
'last_backfill_person_properties_at',
'last_calculation',
'last_error_at',
+ 'last_realtime_cohort_calculation_at',
'pending_version',
'people',
'person_filters_shape_hash',
@@ -158,7 +159,6 @@
'is_static',
'kind',
'last_calculation_duration_ms',
- 'last_realtime_cohort_calculation_at',
'name',
'query',
])
@@ -542,6 +542,7 @@
'last_backfill_person_properties_at',
'last_calculation',
'last_error_at',
+ 'last_realtime_cohort_calculation_at',
'objects',
'pending_version',
'people',
diff --git a/posthog/models/resource_transfer/visitors/cohort.py b/posthog/models/resource_transfer/visitors/cohort.py
index 986af3930e9a..ff028b908764 100644
--- a/posthog/models/resource_transfer/visitors/cohort.py
+++ b/posthog/models/resource_transfer/visitors/cohort.py
@@ -23,6 +23,7 @@ class CohortVisitor(
"last_error_at",
"last_backfill_events_at",
"last_backfill_person_properties_at",
+ "last_realtime_cohort_calculation_at",
"filters_shape_hash",
"behavioral_filters_shape_hash",
"person_filters_shape_hash",
diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.py
index 565387a6e1fd..37d81106b0cf 100644
--- a/posthog/settings/cohorts.py
+++ b/posthog/settings/cohorts.py
@@ -43,26 +43,22 @@ BEHAVIORAL_BACKFILL_FINALIZER_ENABLED: bool = get_from_env(
"BEHAVIORAL_BACKFILL_FINALIZER_ENABLED", False, type_cast=str_to_bool
)
# Whether the finalizer may terminalize person-property runs and stamp
-# `last_backfill_person_properties_at`. Separate from the finalizer gate above, which is already on
-# for behavioral runs, so this is the only thing standing between an enabled person seed path and a
-# live person stamp.
+# `last_backfill_person_properties_at`.
#
-# Keep it off until the flags service stops accepting that stamp as proof the membership table is
-# populated. `Cohort::uses_realtime_membership` takes *either* backfill timestamp, because ~19k
-# cohorts still carry a person stamp written by the legacy realtime workflow before #57545 removed
-# that write, and for those it correctly means "the legacy pipeline computed this cohort into
-# cohort_membership". A stamp written here means something different: only the person half is
-# backfilled. Until the two can be told apart, a person stamp landing on a cohort whose behavioral
-# half is unseeded routes flag evaluation through `cohort_membership` anyway, which under-matches
-# "in cohort" targeting and over-matches negated targeting. `Cohort.is_flag_compatible` fail-closes
-# on this; the flags service does not.
+# Keep it off until every region's flags service runs
+# `REALTIME_COHORT_MEMBERSHIP_STAMP_POLICY=events_or_calculation_stamp`. Under the service's
+# default policy either backfill stamp proves the `cohort_membership` table is populated, but a
+# stamp written here means only the person half is backfilled, so it routes flag evaluation for a
+# cohort whose behavioral half is unseeded through an empty table: "in cohort" targeting matches
+# nobody and negated targeting matches everybody.
#
-# The stamp's other precondition is already met: `cohort_person_shape_changed_supersede` supersedes
-# a cohort's active person-property runs when its person leaves change, so an A->B->A revert can no
-# longer stamp readiness over a backfill whose Stage 2 state went stale in the B window. That fence
-# arms only on saves that maintain the shape hashes: an edit that drops the cohort out of realtime
-# support (`cohort_type` cleared) or a delete/undelete round-trip skips maintenance and supersedes
-# nothing, the same exposure the behavioral fence has.
+# A team in the service's `REALTIME_COHORT_EVALUATION_TEAM_IDS` must also be in
+# `REALTIME_COHORT_TEAM_ALLOWLIST`, because the stamps that service trusts are only invalidated on
+# edit inside the allowlist guard.
+#
+# `cohort_person_shape_changed_supersede` covers the A->B->A revert that would otherwise stamp
+# readiness over a backfill whose Stage 2 state went stale, but only on saves that maintain the
+# shape hashes: an edit clearing `cohort_type` or a delete/undelete round-trip supersedes nothing.
BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED: bool = get_from_env(
"BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED", False, type_cast=str_to_bool
)
diff --git a/products/cohorts/backend/management/commands/compare_cohort_membership.py b/products/cohorts/backend/management/commands/compare_cohort_membership.py
index 59c564dd47f1..9e82b8822c81 100644
--- a/products/cohorts/backend/management/commands/compare_cohort_membership.py
+++ b/products/cohorts/backend/management/commands/compare_cohort_membership.py
@@ -129,7 +129,7 @@ COVERAGE_CAVEATS = (
"the diff is bounded to persons the new pipeline decided on (O); old-only persons outside O are excluded and only probed for missed emissions",
"suspect_missing gates FAIL only where the store provably covers the window (window <= pipeline age, or property-only cohorts); on longer windows unobserved actives are unresolvable until warmup (no snapshot resolves pre-since qualifiers) and report as WARMUP",
"minute/hour-window cohorts get suspect≈0 by construction — the probe cutoff collapses to now",
- "cohorts the old pipeline never recomputed count all only_new as fresh (residual_new is 0 there)",
+ "cohorts with no recompute clock (never recomputed, or the stamp cleared by an edit) count all only_new as fresh (residual_new is 0 there)",
"a partial drain (poll timeout or --max-messages) understates the new side and biases toward FAIL",
)
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 15a890e52768..2660166c1450 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -386,6 +386,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
if person_shape_changed:
self.last_backfill_person_properties_at = None
self._person_shape_changed = True
+ if behavioral_shape_changed or person_shape_changed:
+ # This stamp vouches for the whole-cohort membership computation, so either
+ # kind of leaf-shape change stales it, and nothing recomputes it on a
+ # schedule to notice.
+ self.last_realtime_cohort_calculation_at = None
if maintained_update_fields is None:
return None
@@ -399,6 +404,8 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
maintained_update_fields.add("last_backfill_events_at")
if person_shape_changed:
maintained_update_fields.add("last_backfill_person_properties_at")
+ if behavioral_shape_changed or person_shape_changed:
+ maintained_update_fields.add("last_realtime_cohort_calculation_at")
return maintained_update_fields
except Exception as error:
logger.exception(
diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
index 861e0f25748a..98f3def4faaf 100644
--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
@@ -91,7 +91,10 @@ class TestBehavioralBackfillDependencies(BaseTest):
cohort = self._cohort(7)
old_hash = cohort.filters_shape_hash
old_behavioral_hash = cohort.behavioral_filters_shape_hash
- Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())
+ Cohort.objects.filter(id=cohort.id).update(
+ last_backfill_events_at=timezone.now(),
+ last_realtime_cohort_calculation_at=timezone.now(),
+ )
cohort.refresh_from_db()
cohort.filters = self._filters(30)
@@ -101,6 +104,7 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertNotEqual(cohort.filters_shape_hash, old_hash)
self.assertNotEqual(cohort.behavioral_filters_shape_hash, old_behavioral_hash)
self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertIsNone(cohort.last_realtime_cohort_calculation_at)
def test_positional_filter_update_persists_maintained_fields(self) -> None:
cohort = self._cohort(7)
@@ -120,7 +124,10 @@ class TestBehavioralBackfillDependencies(BaseTest):
cohort = self._cohort(7)
old_hash = cohort.filters_shape_hash
ready_at = timezone.now()
- Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=ready_at)
+ Cohort.objects.filter(id=cohort.id).update(
+ last_backfill_events_at=ready_at,
+ last_realtime_cohort_calculation_at=ready_at,
+ )
cohort.refresh_from_db()
cohort.filters = self._filters(30)
@@ -130,10 +137,14 @@ class TestBehavioralBackfillDependencies(BaseTest):
cohort.refresh_from_db()
self.assertEqual(cohort.filters_shape_hash, old_hash)
self.assertEqual(cohort.last_backfill_events_at, ready_at)
+ self.assertEqual(cohort.last_realtime_cohort_calculation_at, ready_at)
def test_behavioral_edit_nulls_events_readiness(self) -> None:
cohort = self._cohort(7)
- Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())
+ Cohort.objects.filter(id=cohort.id).update(
+ last_backfill_events_at=timezone.now(),
+ last_realtime_cohort_calculation_at=timezone.now(),
+ )
cohort.refresh_from_db()
cohort.filters = self._filters(30)
@@ -141,6 +152,7 @@ class TestBehavioralBackfillDependencies(BaseTest):
cohort.refresh_from_db()
self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertIsNone(cohort.last_realtime_cohort_calculation_at)
def test_person_only_edit_preserves_events_readiness(self) -> None:
cohort = self._cohort(7, person_hash="person-a")
@@ -151,6 +163,7 @@ class TestBehavioralBackfillDependencies(BaseTest):
Cohort.objects.filter(id=cohort.id).update(
last_backfill_events_at=ready_at,
last_backfill_person_properties_at=ready_at,
+ last_realtime_cohort_calculation_at=ready_at,
)
cohort.refresh_from_db()
before = self._orphan_count()
@@ -164,6 +177,9 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertNotEqual(cohort.person_filters_shape_hash, old_person_hash)
self.assertEqual(cohort.last_backfill_events_at, ready_at)
self.assertIsNone(cohort.last_backfill_person_properties_at)
+ # Covers the whole cohort, so a person-only edit stales it even though events
+ # readiness survives.
+ self.assertIsNone(cohort.last_realtime_cohort_calculation_at)
self.assertEqual(self._orphan_count(), before)
def test_first_legacy_save_initializes_hashes_without_invalidating_readiness(self) -> None:
@@ -211,6 +227,7 @@ class TestBehavioralBackfillDependencies(BaseTest):
cohort_type=CohortType.REALTIME,
filters=self._filters(7),
last_backfill_events_at=ready_at,
+ last_realtime_cohort_calculation_at=ready_at,
)
before = self._orphan_count()
@@ -222,6 +239,7 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertIsNone(cohort.behavioral_filters_shape_hash)
self.assertIsNone(cohort.person_filters_shape_hash)
self.assertEqual(cohort.last_backfill_events_at, ready_at)
+ self.assertEqual(cohort.last_realtime_cohort_calculation_at, ready_at)
self.assertEqual(self._orphan_count(), before)
def _redis(self, *set_results: bool) -> mock.Mock:
diff --git a/products/cohorts/backend/parity/classifier.py b/products/cohorts/backend/parity/classifier.py
index 4d6b655848ff..226daafa18f1 100644
--- a/products/cohorts/backend/parity/classifier.py
+++ b/products/cohorts/backend/parity/classifier.py
@@ -146,9 +146,10 @@ def classify_cohort(
# R-FRESH / R-STALE: entries whose flip is newer than the old side's last recompute.
if last_realtime_calculation_at is None:
fresh = len(only_new)
- # stale stays 0: a never-recomputed old side has no entered rows to be stale.
+ # stale stays 0: without a recompute clock nothing bounds which entered rows
+ # could be stale.
if fresh:
- comparison_notes.append("old side never recomputed this cohort; all only_new counted fresh")
+ comparison_notes.append("no recompute clock for the old side; all only_new counted fresh")
else:
fresh = sum(1 for p in only_new if new_state[p].last_updated > last_realtime_calculation_at)
stale = sum(1 for p in only_old if new_state[p].last_updated > last_realtime_calculation_at)
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index 04cac3808543..3f50ac459ea9 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -207,7 +207,7 @@ def _serialize_cohort(cohort: Cohort) -> dict[str, Any]:
HYPERCACHE CONTRACT: These field names must match the Rust Cohort struct in
rust/feature-flags/src/cohorts/cohort_models.rs. Field changes must follow
the expand-and-contract pattern. The contract test will catch mismatches:
- pytest posthog/models/feature_flag/test/test_flags_cache.py -k "test_serializer_output_matches_fixture_schema"
+ pytest products/feature_flags/backend/test/test_flags_cache.py -k "test_serializer_output_matches_fixture_schema"
Note: deleted, is_calculating, is_static, errors_calculating, and groups
are required by the Rust struct (no #[serde(default)]), so omitting them
@@ -237,6 +237,11 @@ def _serialize_cohort(cohort: Cohort) -> dict[str, Any]:
"last_backfill_events_at": (
cohort.last_backfill_events_at.isoformat() if cohort.last_backfill_events_at else None
),
+ "last_realtime_cohort_calculation_at": (
+ cohort.last_realtime_cohort_calculation_at.isoformat()
+ if cohort.last_realtime_cohort_calculation_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 2b03835a73e4..06e618959c12 100644
--- a/products/feature_flags/backend/test/test_flags_cache.py
+++ b/products/feature_flags/backend/test/test_flags_cache.py
@@ -1147,6 +1147,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),
+ last_realtime_cohort_calculation_at=datetime(2024, 1, 15, 12, 0, 0, tzinfo=UTC),
)
# 1) full-flag: exercises all optional nested structures.
@@ -3613,6 +3614,7 @@ class TestSerializeCohort(BaseTest):
team=self.team,
name="Test",
description="A test cohort",
+ last_realtime_cohort_calculation_at=datetime(2024, 1, 15, 12, 0, 0, tzinfo=UTC),
filters={
"properties": {
"type": "OR",
@@ -3622,7 +3624,7 @@ class TestSerializeCohort(BaseTest):
)
result = _serialize_cohort(cohort)
- # Hypercache/service cohort schema: these 19 fields must always be present in the serialized payload
+ # Hypercache/service cohort schema: every one of these fields must be present in the serialized payload
expected_fields = {
"id",
"name",
@@ -3643,6 +3645,7 @@ class TestSerializeCohort(BaseTest):
"condition_type",
"last_backfill_person_properties_at",
"last_backfill_events_at",
+ "last_realtime_cohort_calculation_at",
}
assert set(result.keys()) == expected_fields
assert result["id"] == cohort.id
@@ -3651,6 +3654,10 @@ class TestSerializeCohort(BaseTest):
assert result["deleted"] is False
assert result["is_static"] is False
assert result["is_calculating"] is False
+ assert result["last_realtime_cohort_calculation_at"] == "2024-01-15T12:00:00+00:00"
+
+ cohort.last_realtime_cohort_calculation_at = None
+ assert _serialize_cohort(cohort)["last_realtime_cohort_calculation_at"] is None
@override_settings(FLAGS_REDIS_URL="redis://test")
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index ff0846bb6469..542e66fe2099 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -196,12 +196,12 @@ pub struct Config {
/// `UnknownKind` and skip-commits it without a marker, stranding the run as a shortfall.
/// 2. Flip `SEEDER_PERSON_SEEDS_ENABLED` and let person runs seed.
/// 3. Flip this once step 1 is confirmed everywhere.
- /// 4. Flip Django's `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED` once the remaining
- /// precondition in its `posthog/settings/cohorts.py` docstring holds: the flags service no
- /// longer reads `last_backfill_person_properties_at` as proof `cohort_membership` is
- /// populated. Until then the finalizer skips person runs, so they stay `reconciling` after
- /// step 3 and `seeder_runs_reconciling{kind="person_property"}` climbs. That is expected,
- /// not a stalled dispatch.
+ /// 4. Set `REALTIME_COHORT_MEMBERSHIP_STAMP_POLICY=events_or_calculation_stamp` on every
+ /// region's flags service, then flip Django's
+ /// `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED`. Until that gate opens the finalizer
+ /// skips person runs, so they stay `reconciling` after step 3 and
+ /// `seeder_runs_reconciling{kind="person_property"}` climbs. That is expected, not a
+ /// stalled dispatch.
///
/// Flipping this back off does not undo a bad rollout: a run already in `reconciling` stops
/// being discovered, so it never reaches `reconcile_observed_at` and never finalizes. Recovery
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rs
index bc2d1f954bfc..0e8f7c0be4d7 100644
--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs
+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs
@@ -455,6 +455,7 @@ async fn handle_batch_flag_evaluation(
)
.with_cohort_membership_provider(state.cohort_membership_provider.clone())
.with_realtime_cohort_evaluation(enable_realtime_cohort_evaluation)
+ .with_membership_stamp_policy(state.config.realtime_cohort_membership_stamp_policy)
.with_rayon_dispatcher(state.rayon_dispatcher.clone())
.with_parallel_eval_threshold(state.config.parallel_eval_threshold)
// Read-only: experience-continuity overrides are consulted but never written.
diff --git a/rust/feature-flags/src/cohorts/cohort_cache_manager.rs b/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
index ecc40b045a36..16c8c1e53fec 100644
--- a/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
+++ b/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
@@ -272,6 +272,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
}
}
@@ -769,6 +770,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
};
cohort_cache.cache.insert(1, vec![test_cohort]).await;
// Moka caches update internal stats lazily - sync ensures stats are current
@@ -1137,6 +1139,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
}])
}
}
diff --git a/rust/feature-flags/src/cohorts/cohort_models.rs b/rust/feature-flags/src/cohorts/cohort_models.rs
index 231b1532160f..064a141dfbce 100644
--- a/rust/feature-flags/src/cohorts/cohort_models.rs
+++ b/rust/feature-flags/src/cohorts/cohort_models.rs
@@ -5,6 +5,7 @@ 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")]
@@ -18,7 +19,7 @@ pub enum CohortType {
}
/// HYPERCACHE CONTRACT: These fields are deserialized from JSON written by Python's
-/// `_serialize_cohort()` in posthog/models/feature_flag/flags_cache.py. Field changes
+/// `_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)]
@@ -52,38 +53,122 @@ 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).
+ /// 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>>,
}
-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 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
- /// 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 {
+/// 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!(
- self.cohort_type,
+ cohort.cohort_type,
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()
+ ) && 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",
+ }
+ }
+}
+
+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,
@@ -261,6 +346,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
}
}
@@ -388,7 +474,7 @@ mod tests {
#[test]
#[allow(clippy::type_complexity)]
fn test_uses_realtime_membership() {
- let backfill_ts = Some(Utc::now());
+ let ts = Some(Utc::now());
let behavioral = Some(serde_json::json!({
"person_properties": false, "behavioral": true, "lifecycle": false, "cohorts": false
}));
@@ -396,156 +482,266 @@ mod tests {
"person_properties": true, "behavioral": false, "lifecycle": false, "cohorts": false
}));
- // (cohort_type, person_props_ts, events_ts, condition_type, expected)
+ // (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, None, None, None, false),
- (None, backfill_ts, None, None, false),
- (None, None, backfill_ts, None, false),
- (Some(CohortType::Static), None, None, None, false),
+ (None, ts, ts, ts, behavioral.clone(), false, false),
(
Some(CohortType::Static),
- backfill_ts,
- None,
+ ts,
+ ts,
+ ts,
behavioral.clone(),
false,
+ false,
),
- (Some(CohortType::PersonProperty), None, None, None, false),
(
Some(CohortType::PersonProperty),
- backfill_ts,
- None,
+ ts,
+ ts,
+ ts,
behavioral.clone(),
false,
+ false,
),
- (Some(CohortType::Analytical), None, None, None, false),
(
Some(CohortType::Analytical),
- backfill_ts,
- None,
+ ts,
+ ts,
+ ts,
behavioral.clone(),
false,
+ false,
),
- // Realtime + behavioral condition: either timestamp enables realtime membership
(
Some(CohortType::Realtime),
None,
None,
+ None,
behavioral.clone(),
false,
+ false,
),
(
Some(CohortType::Realtime),
- backfill_ts,
+ ts,
+ None,
None,
behavioral.clone(),
true,
+ false,
),
(
- Some(CohortType::Realtime),
+ Some(CohortType::Behavioral),
+ ts,
+ None,
None,
- backfill_ts,
behavioral.clone(),
true,
+ false,
),
(
Some(CohortType::Realtime),
- backfill_ts,
- backfill_ts,
+ None,
+ ts,
+ None,
behavioral.clone(),
true,
+ true,
),
- // Behavioral + behavioral condition: either timestamp enables realtime membership
(
- Some(CohortType::Behavioral),
+ Some(CohortType::Realtime),
None,
None,
+ ts,
behavioral.clone(),
false,
+ true,
),
(
Some(CohortType::Behavioral),
- backfill_ts,
None,
+ None,
+ ts,
behavioral.clone(),
- true,
+ false,
+ false,
),
+ // The events stamp carries a `behavioral`-typed cohort that the calculation
+ // stamp above cannot.
(
Some(CohortType::Behavioral),
None,
- backfill_ts,
+ ts,
+ 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,
+ ts,
+ ts,
+ ts,
+ behavioral.clone(),
+ true,
+ true,
),
(
Some(CohortType::Realtime),
- backfill_ts,
- backfill_ts,
+ ts,
+ ts,
+ 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,
),
+ (Some(CohortType::Realtime), ts, ts, ts, None, false, false),
];
- for (cohort_type, pp_ts, events_ts, condition_type, expected) in cases {
+ 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 = pp_ts;
+ 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!(
- cohort.uses_realtime_membership(),
+ input.parse::<MembershipStampPolicy>().unwrap(),
expected,
- "cohort_type={cohort_type:?}, pp_ts={}, events_ts={}, condition_type={condition_type:?} should return {expected}",
- pp_ts.is_some(),
- events_ts.is_some()
+ "{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() {
- // Verifies that filtering cohorts by `uses_realtime_membership()` correctly
- // 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.
+ // 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
@@ -606,7 +802,7 @@ mod tests {
let realtime_ids: Vec<i32> = cohorts
.iter()
- .filter(|c| c.uses_realtime_membership())
+ .filter(|c| MembershipStampPolicy::default().uses_realtime_membership(c))
.map(|c| c.id)
.collect();
@@ -705,6 +901,7 @@ mod skip_serializing_if_tests {
"cohort_type",
"last_backfill_person_properties_at",
"condition_type",
+ "last_realtime_cohort_calculation_at",
] {
assert_absent(&output, key);
}
@@ -725,6 +922,7 @@ mod skip_serializing_if_tests {
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
})),
@@ -742,6 +940,7 @@ 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!(output["last_realtime_cohort_calculation_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 edc502d76b97..5e6fe5eccb36 100644
--- a/rust/feature-flags/src/cohorts/cohort_operations.rs
+++ b/rust/feature-flags/src/cohorts/cohort_operations.rs
@@ -3,16 +3,19 @@ use serde_json::Value;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::collections::HashSet;
-use std::sync::Mutex;
+use std::sync::{Mutex, RwLock};
use super::cohort_models::CohortPropertyType;
use super::cohort_models::CohortValues;
use crate::cohorts::cohort_cache_manager::CohortFetchError;
use crate::cohorts::cohort_models::{
- Cohort, CohortId, CohortProperty, CohortValuesItem, InnerCohortProperty,
+ Cohort, CohortId, CohortProperty, CohortValuesItem, InnerCohortProperty, MembershipStampPolicy,
};
use crate::database::get_connection_with_metrics;
-use crate::metrics::consts::{COHORT_MALFORMED_FILTER_COUNTER, COHORT_UNSUPPORTED_FILTER_COUNTER};
+use crate::metrics::consts::{
+ COHORT_MALFORMED_FILTER_COUNTER, COHORT_UNSUPPORTED_FILTER_COUNTER,
+ FLAG_COHORT_STAMP_POLICY_DIVERGENCE_COUNTER,
+};
use crate::properties::property_matching::match_property;
use crate::properties::property_models::OperatorType;
use crate::utils::graph_utils::{DependencyGraph, DependencyProvider, DependencyType};
@@ -52,13 +55,60 @@ fn record_malformed_cohort_filter(cohort_id: CohortId, team_id: TeamId, phase: &
}
}
+/// Cohorts already warned about by `record_stamp_policy_divergence`, deduped as
+/// `WARNED_MALFORMED_COHORTS` above is. An `RwLock` because divergence is common rather
+/// than exceptional, so past the first warn every request takes only the read side.
+static WARNED_DIVERGENT_COHORTS: Lazy<RwLock<HashSet<(TeamId, CohortId)>>> =
+ Lazy::new(|| RwLock::new(HashSet::new()));
+
+/// Counts and logs a cohort the two membership stamp policies route differently. The
+/// counter carries no ids (cardinality), so the deduped log is the only place to learn
+/// which cohort diverged.
+pub(crate) fn record_stamp_policy_divergence(
+ cohort: &Cohort,
+ active_policy: MembershipStampPolicy,
+) {
+ let Some(divergence) = MembershipStampPolicy::divergence(cohort) else {
+ return;
+ };
+ common_metrics::inc(
+ FLAG_COHORT_STAMP_POLICY_DIVERGENCE_COUNTER,
+ &[
+ ("direction".to_string(), divergence.as_label().to_string()),
+ (
+ "active_policy".to_string(),
+ active_policy.as_label().to_string(),
+ ),
+ ],
+ 1,
+ );
+
+ if WARNED_DIVERGENT_COHORTS
+ .read()
+ .unwrap()
+ .contains(&(cohort.team_id, cohort.id))
+ {
+ return;
+ }
+ let mut warned = WARNED_DIVERGENT_COHORTS.write().unwrap();
+ if warned.insert((cohort.team_id, cohort.id)) {
+ tracing::warn!(
+ cohort_id = cohort.id,
+ team_id = cohort.team_id,
+ direction = divergence.as_label(),
+ active_policy = active_policy.as_label(),
+ "Membership stamp policies disagree on this cohort's realtime routing; the REALTIME_COHORT_MEMBERSHIP_STAMP_POLICY flip would change it"
+ );
+ }
+}
+
/// Column list for `posthog_cohort` queries. Must match the fields in `Cohort` (sqlx::FromRow).
const COHORT_COLUMNS: &str = r#"
c.id, c.name, c.description, c.team_id, c.deleted, c.filters,
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.condition_type
+ c.condition_type, c.last_realtime_cohort_calculation_at
"#;
impl Cohort {
@@ -551,6 +601,7 @@ impl DependencyProvider for Cohort {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::cohorts::cohort_models::CohortType;
use crate::utils::test_utils::TestContext;
use serde_json::json;
@@ -664,6 +715,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
};
// This should not fail even though the filters are malformed
@@ -693,6 +745,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
};
let dependencies = static_cohort_empty_filters.extract_dependencies().unwrap();
@@ -719,6 +772,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
};
// This should fail because it's dynamic and the filters are malformed
@@ -766,6 +820,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
}
}
@@ -815,6 +870,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
};
// Create a dynamic cohort (cohort 20) that depends on the static cohort
@@ -851,6 +907,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
};
let cohorts = vec![static_cohort, dynamic_cohort];
@@ -947,6 +1004,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
};
let cohorts = vec![cohort];
@@ -1021,6 +1079,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
};
let cohorts = vec![cohort_with_negation];
@@ -1114,9 +1173,36 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_at: None,
}
}
+ #[test]
+ fn test_record_stamp_policy_divergence_only_records_divergent_cohorts() {
+ let behavioral = json!({
+ "person_properties": false, "behavioral": true, "lifecycle": false, "cohorts": false
+ });
+ let routed = |id| {
+ let mut cohort = create_dynamic_cohort_with_filters(id, json!({}));
+ cohort.cohort_type = Some(CohortType::Realtime);
+ cohort.condition_type = Some(behavioral.clone());
+ cohort
+ };
+
+ let mut divergent = routed(987_654);
+ divergent.last_backfill_person_properties_at = Some(chrono::Utc::now());
+ record_stamp_policy_divergence(&divergent, MembershipStampPolicy::AnyBackfillStamp);
+ record_stamp_policy_divergence(&divergent, MembershipStampPolicy::AnyBackfillStamp);
+
+ let mut agreed = routed(987_655);
+ agreed.last_backfill_events_at = Some(chrono::Utc::now());
+ record_stamp_policy_divergence(&agreed, MembershipStampPolicy::AnyBackfillStamp);
+
+ let warned = WARNED_DIVERGENT_COHORTS.read().unwrap();
+ assert!(warned.contains(&(divergent.team_id, divergent.id)));
+ assert!(!warned.contains(&(agreed.team_id, agreed.id)));
+ }
+
#[test]
fn test_extract_dependencies_with_flat_and_nested_filters() {
// Cohorts created via the API can place property filters (including cohort
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index f0ec83791f4e..da99a6c62b16 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -1,3 +1,4 @@
+use crate::cohorts::cohort_models::MembershipStampPolicy;
use common_continuous_profiling::ContinuousProfilingConfig;
use common_cookieless::CookielessConfig;
use common_types::TeamId;
@@ -393,16 +394,27 @@ pub struct Config {
// 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>`) for every team in REALTIME_COHORT_EVALUATION_TEAM_IDS, including any
- // already allowlisted at deploy time — otherwise its behavioral cohorts read as
- // condition_type = NULL and fall back to legacy dynamic evaluation, which resolves every
- // person as a non-member rather than just evaluating slower.
+ // Routing also requires `condition_type`, which was never backfilled, so every team listed
+ // here needs `python manage.py resave_cohorts --team-id <id>` first. Without it behavioral
+ // cohorts read as condition_type = NULL and fall back to dynamic evaluation, which resolves
+ // every person as a non-member rather than just evaluating slower.
+ //
+ // A team listed here must also be in Django's REALTIME_COHORT_TEAM_ALLOWLIST: the stamps
+ // this predicate trusts are only invalidated on edit for allowlisted teams, so without it
+ // an edited cohort keeps routing to a membership table computed for its old definition.
#[envconfig(from = "REALTIME_COHORT_EVALUATION_TEAM_IDS", default = "none")]
pub realtime_cohort_evaluation_team_ids: TeamIdCollection,
+ // Which cohort stamps the routing predicate accepts as proof the PG `cohort_membership`
+ // table is populated (see `MembershipStampPolicy`). "any_backfill_stamp" also accepts the
+ // overloaded `last_backfill_person_properties_at`; "events_or_calculation_stamp" does not,
+ // and is what Django's BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED gate waits on.
+ #[envconfig(
+ from = "REALTIME_COHORT_MEMBERSHIP_STAMP_POLICY",
+ default = "any_backfill_stamp"
+ )]
+ pub realtime_cohort_membership_stamp_policy: MembershipStampPolicy,
+
// Cache TTL for realtime cohort membership lookups (seconds).
#[envconfig(from = "COHORT_MEMBERSHIP_CACHE_TTL_SECONDS", default = "60")]
pub cohort_membership_cache_ttl_seconds: u64,
@@ -1054,6 +1066,7 @@ impl Config {
flags_secret_keys: String::new(),
secret_key: "test-secret-key-at-least-32-bytes-long".to_string(),
realtime_cohort_evaluation_team_ids: TeamIdCollection::None,
+ realtime_cohort_membership_stamp_policy: MembershipStampPolicy::default(),
cohort_membership_cache_ttl_seconds: 60,
cohort_membership_cache_max_entries: 50_000,
realtime_cohort_lookup_timeout_ms: 1000,
diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rs
index 72dbd3b1bd8b..67796ef25108 100644
--- a/rust/feature-flags/src/flags/cache_builder.rs
+++ b/rust/feature-flags/src/flags/cache_builder.rs
@@ -1,7 +1,7 @@
//! Cache builder logic for producing the hypercache flags payload.
//!
//! Rust equivalent of Python's `_get_feature_flags_for_service()` in
-//! `posthog/models/feature_flag/flags_cache.py`. Reads flags and cohorts from
+//! `products/feature_flags/backend/flags_cache.py`. Reads flags and cohorts from
//! Postgres, computes evaluation metadata (dependency stages via Kahn's algorithm),
//! and produces the `HypercacheFlagsWrapper` JSON payload.
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rs
index 2e85560d0454..16870cf55c1f 100644
--- a/rust/feature-flags/src/flags/feature_flag_list.rs
+++ b/rust/feature-flags/src/flags/feature_flag_list.rs
@@ -1258,6 +1258,10 @@ mod tests {
cohorts[0].last_backfill_person_properties_at.is_some(),
"last_backfill_person_properties_at should deserialize from ISO 8601 timestamp"
);
+ assert!(
+ cohorts[0].last_realtime_cohort_calculation_at.is_some(),
+ "last_realtime_cohort_calculation_at should deserialize from ISO 8601 timestamp"
+ );
// Verify cohort filters can parse into the expected CohortProperty structure
let filters_value = cohorts[0]
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index 529e1c626bc9..13127b43eaf5 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -1,8 +1,10 @@
use crate::api::errors::FlagError;
use crate::api::types::{FlagDetails, FlagValue, FlagsResponse, FromFeatureAndMatch};
use crate::cohorts::cohort_cache_manager::CohortCacheManager;
-use crate::cohorts::cohort_models::{Cohort, CohortId};
-use crate::cohorts::cohort_operations::{apply_cohort_membership_logic, evaluate_dynamic_cohorts};
+use crate::cohorts::cohort_models::{Cohort, CohortId, MembershipStampPolicy};
+use crate::cohorts::cohort_operations::{
+ apply_cohort_membership_logic, evaluate_dynamic_cohorts, record_stamp_policy_divergence,
+};
use crate::cohorts::membership::{CohortMembershipProvider, NoOpCohortMembershipProvider};
use crate::database::PostgresRouter;
use crate::flags::flag_group_type_mapping::{
@@ -334,6 +336,7 @@ pub struct FeatureFlagMatcher {
/// Whether to enable realtime cohort evaluation.
/// When false, realtime cohorts are treated as non-members.
enable_realtime_cohort_evaluation: bool,
+ membership_stamp_policy: MembershipStampPolicy,
/// Cohort definitions preloaded from the flags hypercache.
/// When present, scoped to only the cohorts referenced by flags (including transitive deps),
/// so the matcher skips the CohortCacheManager PG query entirely.
@@ -411,6 +414,7 @@ impl FeatureFlagMatcher {
skip_writes: false,
filtered_out_flag_ids: HashSet::new(),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
preloaded_cohorts: None,
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -454,6 +458,11 @@ impl FeatureFlagMatcher {
self
}
+ pub fn with_membership_stamp_policy(mut self, policy: MembershipStampPolicy) -> Self {
+ self.membership_stamp_policy = policy;
+ self
+ }
+
pub fn with_detailed_analysis(mut self, detailed_analysis: bool) -> Self {
self.detailed_analysis = detailed_analysis;
self
@@ -2054,7 +2063,7 @@ impl FeatureFlagMatcher {
debug_assert!(
!cohorts
.iter()
- .any(|c| c.is_static && c.uses_realtime_membership()),
+ .any(|c| c.is_static && self.membership_stamp_policy.uses_realtime_membership(c)),
"Cohort cannot be both static and realtime"
);
let static_cohort_ids: Vec<CohortId> = cohorts
@@ -2110,7 +2119,8 @@ impl FeatureFlagMatcher {
let realtime_cohort_ids: Vec<CohortId> = if self.enable_realtime_cohort_evaluation {
cohorts
.iter()
- .filter(|c| c.uses_realtime_membership())
+ .inspect(|c| record_stamp_policy_divergence(c, self.membership_stamp_policy))
+ .filter(|c| self.membership_stamp_policy.uses_realtime_membership(c))
.map(|c| c.id)
.collect()
} else {
diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rs
index cfa37c22e2f1..75aa005f9521 100644
--- a/rust/feature-flags/src/flags/flag_models.rs
+++ b/rust/feature-flags/src/flags/flag_models.rs
@@ -102,9 +102,9 @@ impl EvaluationMetadata {
/// which places all flags in one evaluation stage with empty transitive deps.
///
/// HYPERCACHE CONTRACT: These fields must match the top-level keys returned by
-/// `_get_feature_flags_for_service()` in posthog/models/feature_flag/flags_cache.py.
+/// `_get_feature_flags_for_service()` in products/feature_flags/backend/flags_cache.py.
/// Field changes must follow the expand-and-contract pattern — see contract tests in
-/// posthog/models/feature_flag/test/test_flags_cache.py.
+/// products/feature_flags/backend/test/test_flags_cache.py.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HypercacheFlagsWrapper {
pub flags: Vec<FeatureFlag>,
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index 25135f647037..64182145da7e 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -13,7 +13,7 @@ mod tests {
api::types::{FlagValue, LegacyFlagsResponse},
cohorts::{
cohort_cache_manager::CohortCacheManager,
- cohort_models::{CohortId, CohortType},
+ cohort_models::{CohortId, CohortType, MembershipStampPolicy},
membership::{CohortMembershipError, CohortMembershipProvider},
},
flags::{
@@ -3595,6 +3595,7 @@ mod tests {
Some(Utc::now()),
None,
Some(behavioral_condition_type()),
+ None,
)
.await
.unwrap();
@@ -3661,6 +3662,7 @@ mod tests {
Some(Utc::now()),
None,
Some(behavioral_condition_type()),
+ None,
)
.await
.unwrap();
@@ -3772,6 +3774,144 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn test_disambiguated_policy_person_stamp_only_falls_back_to_dynamic() {
+ let context = TestContext::new(None).await;
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ let team = context.insert_new_team(None).await.unwrap();
+
+ // The person satisfies the filters and the provider reports non-membership, so a
+ // match can only have come from dynamic evaluation.
+ let cohort = context
+ .insert_cohort_with_type_and_condition_type(
+ team.id,
+ Some("Person Stamp Only Cohort".to_string()),
+ plan_cohort_filters("enterprise"),
+ false,
+ Some(CohortType::Realtime),
+ Some(Utc::now()),
+ None,
+ Some(behavioral_condition_type()),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let distinct_id = "person_stamp_only_user".to_string();
+ context
+ .insert_person(
+ team.id,
+ distinct_id.clone(),
+ Some(json!({"plan": "enterprise"})),
+ )
+ .await
+ .unwrap();
+
+ let flag = flag_targeting_cohort(team.id, cohort.id);
+
+ let provider = Arc::new(FixedMembershipProvider::new(HashMap::from([(
+ cohort.id, false,
+ )])));
+ let mut matcher = FeatureFlagMatcher::new(
+ distinct_id.clone(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ empty_group_type_cache(),
+ None,
+ )
+ .with_cohort_membership_provider(provider.clone())
+ .with_realtime_cohort_evaluation(true)
+ .with_membership_stamp_policy(MembershipStampPolicy::EventsOrCalculationStamp);
+
+ matcher
+ .prepare_flag_evaluation_state(&[&flag])
+ .await
+ .unwrap();
+
+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();
+
+ assert!(
+ result.matches,
+ "A person-stamp-only cohort must evaluate dynamically under the disambiguated policy"
+ );
+ assert_eq!(
+ provider.calls.load(Ordering::SeqCst),
+ 0,
+ "Provider must not be consulted for a cohort only the overloaded person stamp vouches for"
+ );
+ }
+
+ #[tokio::test]
+ async fn test_disambiguated_policy_calculation_stamp_consults_provider() {
+ let context = TestContext::new(None).await;
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ let team = context.insert_new_team(None).await.unwrap();
+
+ // The person's plan is free, so dynamic evaluation cannot match and a match proves
+ // both the provider was consulted and the stamp round-tripped through PG.
+ let cohort = context
+ .insert_cohort_with_type_and_condition_type(
+ team.id,
+ Some("Calc Stamp Cohort".to_string()),
+ plan_cohort_filters("enterprise"),
+ false,
+ Some(CohortType::Realtime),
+ None,
+ None,
+ Some(behavioral_condition_type()),
+ Some(Utc::now()),
+ )
+ .await
+ .unwrap();
+
+ let distinct_id = "calc_stamp_user".to_string();
+ context
+ .insert_person(team.id, distinct_id.clone(), Some(json!({"plan": "free"})))
+ .await
+ .unwrap();
+
+ let flag = flag_targeting_cohort(team.id, cohort.id);
+
+ let provider = Arc::new(FixedMembershipProvider::new(HashMap::from([(
+ cohort.id, true,
+ )])));
+ let mut matcher = FeatureFlagMatcher::new(
+ distinct_id.clone(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ empty_group_type_cache(),
+ None,
+ )
+ .with_cohort_membership_provider(provider.clone())
+ .with_realtime_cohort_evaluation(true)
+ .with_membership_stamp_policy(MembershipStampPolicy::EventsOrCalculationStamp);
+
+ matcher
+ .prepare_flag_evaluation_state(&[&flag])
+ .await
+ .unwrap();
+
+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();
+
+ assert!(
+ result.matches,
+ "A calculation-stamped cohort must route through the provider under the disambiguated policy"
+ );
+ assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
+ }
+
#[tokio::test]
async fn test_evaluate_feature_flags_with_experience_continuity() {
let context = TestContext::new(None).await;
diff --git a/rust/feature-flags/src/handler/evaluation.rs b/rust/feature-flags/src/handler/evaluation.rs
index a866756140e9..2927df7fa55a 100644
--- a/rust/feature-flags/src/handler/evaluation.rs
+++ b/rust/feature-flags/src/handler/evaluation.rs
@@ -34,6 +34,7 @@ pub async fn evaluate_feature_flags(
.with_rayon_dispatcher(context.rayon_dispatcher)
.with_skip_writes(context.skip_writes)
.with_realtime_cohort_evaluation(context.enable_realtime_cohort_evaluation)
+ .with_membership_stamp_policy(context.membership_stamp_policy)
.with_detailed_analysis(context.detailed_analysis)
.with_only_use_override_person_properties(context.only_use_override_person_properties)
.with_timezone(context.team_timezone);
diff --git a/rust/feature-flags/src/handler/flags.rs b/rust/feature-flags/src/handler/flags.rs
index 8f17cd332fce..7078291cb519 100644
--- a/rust/feature-flags/src/handler/flags.rs
+++ b/rust/feature-flags/src/handler/flags.rs
@@ -392,6 +392,7 @@ pub async fn evaluate_for_request(
.config
.realtime_cohort_evaluation_team_ids
.includes_team(team_id),
+ membership_stamp_policy: state.config.realtime_cohort_membership_stamp_policy,
detailed_analysis: detailed_analysis.unwrap_or(false),
only_use_override_person_properties: only_use_override_person_properties.unwrap_or(false),
};
diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rs
index 9df0b21aed9e..0c116c47e964 100644
--- a/rust/feature-flags/src/handler/tests.rs
+++ b/rust/feature-flags/src/handler/tests.rs
@@ -8,6 +8,7 @@ use crate::{
},
},
cohorts::cohort_cache_manager::CohortCacheManager,
+ cohorts::cohort_models::MembershipStampPolicy,
cohorts::membership::{
CohortMembershipError, CohortMembershipProvider, NoOpCohortMembershipProvider,
},
@@ -222,6 +223,7 @@ async fn test_evaluate_feature_flags() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -307,6 +309,7 @@ async fn test_evaluate_feature_flags_with_errors() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -699,6 +702,7 @@ async fn test_evaluate_feature_flags_multiple_flags() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -782,6 +786,7 @@ async fn test_evaluate_feature_flags_details() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -938,6 +943,7 @@ async fn test_evaluate_feature_flags_with_overrides() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -1020,6 +1026,7 @@ async fn test_long_distinct_id() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -1627,6 +1634,7 @@ async fn test_parallel_path_matches_sequential_results() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -1658,6 +1666,7 @@ async fn test_parallel_path_matches_sequential_results() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -1750,6 +1759,7 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {
skip_writes: false,
cohort_membership_provider: provider_disabled.clone(),
enable_realtime_cohort_evaluation: false,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
@@ -1787,6 +1797,7 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {
skip_writes: false,
cohort_membership_provider: provider_enabled.clone(),
enable_realtime_cohort_evaluation: true,
+ membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
};
diff --git a/rust/feature-flags/src/handler/types.rs b/rust/feature-flags/src/handler/types.rs
index 0d0346e60338..d255bc5c0625 100644
--- a/rust/feature-flags/src/handler/types.rs
+++ b/rust/feature-flags/src/handler/types.rs
@@ -13,7 +13,10 @@ use uuid::Uuid;
use crate::{
api::types::FlagsQueryParams,
- cohorts::{cohort_cache_manager::CohortCacheManager, membership::CohortMembershipProvider},
+ cohorts::{
+ cohort_cache_manager::CohortCacheManager, cohort_models::MembershipStampPolicy,
+ membership::CohortMembershipProvider,
+ },
flags::{flag_group_type_mapping::GroupTypeCacheManager, flag_models::FeatureFlagList},
rayon_dispatcher::RayonDispatcher,
router,
@@ -94,6 +97,7 @@ pub struct FeatureFlagEvaluationContext {
pub cohort_membership_provider: Arc<dyn CohortMembershipProvider>,
/// Whether to enable realtime cohort evaluation.
pub enable_realtime_cohort_evaluation: bool,
+ pub membership_stamp_policy: MembershipStampPolicy,
/// Whether to include detailed condition analysis in flag evaluation results.
pub detailed_analysis: bool,
/// Whether to only use person properties from request payload, ignoring database properties.
diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rs
index 0e6ce4c3f1a2..65da8c5149fd 100644
--- a/rust/feature-flags/src/metrics/consts.rs
+++ b/rust/feature-flags/src/metrics/consts.rs
@@ -29,6 +29,12 @@ pub const COHORT_UNSUPPORTED_FILTER_COUNTER: &str = "flags_cohort_unsupported_fi
// structural errors. Cohort and team ids are in the companion debug log, not metric
// labels (cardinality).
pub const COHORT_MALFORMED_FILTER_COUNTER: &str = "flags_cohort_malformed_filter_total";
+// Counts evaluated cohorts the two MembershipStampPolicy variants route differently.
+// Labels: direction="would_lose" | "would_gain", active_policy = the policy this process
+// runs, which says whether the reroute is still pending or already applied. Cohort and
+// team ids are in the companion deduped warn log (cardinality).
+pub const FLAG_COHORT_STAMP_POLICY_DIVERGENCE_COUNTER: &str =
+ "flags_cohort_stamp_policy_divergence_total";
// Realtime cohort membership cache (CachedCohortMembershipProvider, keyed on
// (team_id, person_uuid)). hit = lookup fully served from cache; miss = a
// behavioral cohorts DB query was issued (no cache entry, or the entry was
diff --git a/rust/feature-flags/src/utils/mock.rs b/rust/feature-flags/src/utils/mock.rs
index 51485360f2c2..aeb31e68e4ba 100644
--- a/rust/feature-flags/src/utils/mock.rs
+++ b/rust/feature-flags/src/utils/mock.rs
@@ -418,6 +418,7 @@ mod tests {
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
condition_type: None,
+ last_realtime_cohort_calculation_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.rs
index 211d136dfa20..798a87506cb5 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -821,6 +821,7 @@ pub async fn insert_cohort_for_team_in_pg(
last_backfill_person_properties_at: Option<DateTime<Utc>>,
last_backfill_events_at: Option<DateTime<Utc>>,
condition_type: Option<serde_json::Value>,
+ last_realtime_cohort_calculation_at: Option<DateTime<Utc>>,
) -> Result<Cohort, Error> {
let cohort = Cohort {
id: 0, // Placeholder, will be updated after insertion
@@ -842,13 +843,14 @@ pub async fn insert_cohort_for_team_in_pg(
last_backfill_person_properties_at,
last_backfill_events_at,
condition_type,
+ last_realtime_cohort_calculation_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, 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)
+ (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, last_realtime_cohort_calculation_at) VALUES
+ ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
RETURNING id"#,
)
.bind(&cohort.name)
@@ -869,6 +871,7 @@ pub async fn insert_cohort_for_team_in_pg(
.bind(cohort.last_backfill_person_properties_at)
.bind(cohort.last_backfill_events_at)
.bind(&cohort.condition_type)
+ .bind(cohort.last_realtime_cohort_calculation_at)
.fetch_one(&mut *conn)
.await?;
@@ -1288,6 +1291,7 @@ impl TestContext {
None,
None,
None,
+ None,
)
.await
}
@@ -1313,14 +1317,13 @@ impl TestContext {
last_backfill_person_properties_at,
last_backfill_events_at,
None,
+ 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.
+ /// Like `insert_cohort_with_type`, but also sets `condition_type` and the legacy
+ /// calculation stamp, both of which the realtime membership routing predicate reads.
#[allow(clippy::too_many_arguments)]
pub async fn insert_cohort_with_type_and_condition_type(
&self,
@@ -1332,6 +1335,7 @@ impl TestContext {
last_backfill_person_properties_at: Option<DateTime<Utc>>,
last_backfill_events_at: Option<DateTime<Utc>>,
condition_type: Option<serde_json::Value>,
+ last_realtime_cohort_calculation_at: Option<DateTime<Utc>>,
) -> Result<Cohort, Error> {
insert_cohort_for_team_in_pg(
self.non_persons_writer.clone(),
@@ -1343,6 +1347,7 @@ impl TestContext {
last_backfill_person_properties_at,
last_backfill_events_at,
condition_type,
+ last_realtime_cohort_calculation_at,
)
.await
}
diff --git a/rust/feature-flags/tests/fixtures/hypercache_contract.json b/rust/feature-flags/tests/fixtures/hypercache_contract.json
index 3934be21a6d4..bea8259d3432 100644
--- a/rust/feature-flags/tests/fixtures/hypercache_contract.json
+++ b/rust/feature-flags/tests/fixtures/hypercache_contract.json
@@ -220,7 +220,8 @@
"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"
+ "last_backfill_events_at": "2024-01-15T12:00:00+00:00",
+ "last_realtime_cohort_calculation_at": "2024-01-15T12:00:00+00:00"
}
]
}