Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cohorts): consult correct fields for time windows (#66394)

Matheus Batista4f45a2132ee8
diff --git a/rust/cohort-stream-processor/src/filters/leaf_classifier.rs b/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
index 02b78845d70a..46ea4fdda70f 100644
--- a/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
+++ b/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
@@ -315,6 +315,79 @@ mod tests {
}
}
+ #[test]
+ fn performed_event_multiple_explicit_relative_lower_window_is_kept() {
+ use crate::stage1::state::StateVariant;
+ // The cohort UI stores "in the last N days" as `explicit_datetime: "-Nd"` with no
+ // time_interval/time_value; the multiple path must resolve it like the single path does.
+ for (explicit_datetime, expected_variant, why) in [
+ (
+ "-7d",
+ StateVariant::BehavioralDailyBuckets,
+ "-7d → 7 days → daily",
+ ),
+ (
+ "-1y",
+ StateVariant::BehavioralCompressedHistory,
+ "-1y → 365 days → compressed",
+ ),
+ ] {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "explicit_datetime": explicit_datetime,
+ "operator": "gte",
+ "operator_value": 3,
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ panic!("an explicit relative-lower multiple is kept: {why}");
+ };
+ assert_eq!(leaf.value, BehavioralValue::PerformedEventMultiple);
+ assert_eq!(leaf.explicit_datetime.as_deref(), Some(explicit_datetime));
+ assert_eq!(leaf.state_variant, Some(expected_variant), "{why}");
+ }
+ }
+
+ #[test]
+ fn performed_event_multiple_explicit_unrepresentable_window_is_dropped() {
+ // Sub-day and absolute-range explicit windows have no whole-day sliding form, so the leaf
+ // drops exactly as it did before explicit_datetime was consulted (which dropped all of them).
+ for (from, to, why) in [
+ (
+ "-2h",
+ Value::Null,
+ "sub-day relative window → unsupported variant",
+ ),
+ (
+ "2026-01-01",
+ json!("2026-12-31"),
+ "absolute range → unsupported variant",
+ ),
+ ] {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "explicit_datetime": from,
+ "explicit_datetime_to": to,
+ "operator": "gte",
+ "operator_value": 3,
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ assert!(
+ matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::UnsupportedStateVariant)
+ ),
+ "{why}",
+ );
+ }
+ }
+
#[test]
fn performed_event_without_window_is_dropped_as_unsupported_variant() {
let node = json!({
diff --git a/rust/cohort-stream-processor/src/filters/reverse_index.rs b/rust/cohort-stream-processor/src/filters/reverse_index.rs
index 6f1aae003039..6d0fa0f706cc 100644
--- a/rust/cohort-stream-processor/src/filters/reverse_index.rs
+++ b/rust/cohort-stream-processor/src/filters/reverse_index.rs
@@ -400,6 +400,27 @@ mod tests {
})
}
+ /// A `performed_event_multiple` leaf whose window comes from `explicit_datetime`(_to) rather than
+ /// `time_value`/`time_interval` (pass `Value::Null` for an absent `_to`).
+ fn behavioral_performed_event_multiple_explicit(
+ explicit_datetime: &str,
+ explicit_datetime_to: Value,
+ operator: &str,
+ operator_value: i64,
+ ) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "explicit_datetime": explicit_datetime,
+ "explicit_datetime_to": explicit_datetime_to,
+ "operator": operator,
+ "operator_value": operator_value,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": behavioral_bytecode(),
+ })
+ }
+
fn person_leaf() -> Value {
json!({
"type": "person",
@@ -596,6 +617,109 @@ mod tests {
);
}
+ #[test]
+ fn freeze_explicit_relative_lower_multiple_carries_window_days_and_op() {
+ // The UI stores "in the last N days" as `explicit_datetime: "-Nd"`; the frozen metadata must
+ // carry the resolved window days and predicate op so the worker can bucket and compare.
+ for (explicit_datetime, expected_variant, expected_days, why) in [
+ (
+ "-30d",
+ StateVariant::BehavioralDailyBuckets,
+ 30,
+ "-30d → 30 days → daily",
+ ),
+ (
+ "-1y",
+ StateVariant::BehavioralCompressedHistory,
+ 365,
+ "-1y → 365 days → compressed",
+ ),
+ ] {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event_multiple_explicit(
+ explicit_datetime,
+ Value::Null,
+ "gte",
+ 3,
+ )]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let lsk = frozen.by_condition_to_lsk[&HASH][0];
+ let meta = frozen.by_lsk[&lsk];
+ assert_eq!(meta.variant, expected_variant, "{why}");
+ assert_eq!(meta.window, None, "{why}");
+ assert_eq!(meta.window_days, Some(expected_days), "{why}");
+ assert_eq!(meta.predicate_op, Some(PredicateOp::Gte(3)), "{why}");
+ }
+ }
+
+ #[test]
+ fn freeze_drops_an_explicit_absolute_range_multiple() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event_multiple_explicit(
+ "2026-01-01",
+ json!("2026-12-31"),
+ "gte",
+ 3,
+ )]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+ assert!(
+ frozen.by_lsk.is_empty(),
+ "an absolute-range multiple has no sliding window and leaves no worker metadata",
+ );
+ }
+
+ #[test]
+ fn freeze_explicit_relative_lower_matches_the_time_value_interval_window_days() {
+ // A relative `explicit_datetime` and the equivalent `time_value`/`time_interval` resolve to the
+ // same frozen window metadata — they are the same oracle query.
+ let mut explicit_builder = TeamFiltersBuilder::default();
+ explicit_builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event_multiple_explicit(
+ "-30d",
+ Value::Null,
+ "gte",
+ 3,
+ )]),
+ )
+ .unwrap();
+ let explicit = explicit_builder.freeze(UTC);
+ let explicit_meta = explicit.by_lsk[&explicit.by_condition_to_lsk[&HASH][0]];
+
+ let mut interval_builder = TeamFiltersBuilder::default();
+ interval_builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event_multiple(
+ 30, "day", "gte", 3,
+ )]),
+ )
+ .unwrap();
+ let interval = interval_builder.freeze(UTC);
+ let interval_meta = interval.by_lsk[&interval.by_condition_to_lsk[&HASH][0]];
+
+ assert_eq!(explicit_meta.window_days, Some(30));
+ assert_eq!(explicit_meta.window_days, interval_meta.window_days);
+ assert_eq!(explicit_meta.variant, interval_meta.variant);
+ assert_eq!(explicit_meta.predicate_op, interval_meta.predicate_op);
+ }
+
#[test]
fn freeze_partitions_conditions_by_kind() {
let mut builder = TeamFiltersBuilder::default();
diff --git a/rust/cohort-stream-processor/src/stage1/pick_state.rs b/rust/cohort-stream-processor/src/stage1/pick_state.rs
index d38a6892d2b2..0a0aaf880fa5 100644
--- a/rust/cohort-stream-processor/src/stage1/pick_state.rs
+++ b/rust/cohort-stream-processor/src/stage1/pick_state.rs
@@ -359,9 +359,20 @@ fn relative_window_from_interval(
}
}
-/// The whole-day window for a `performed_event_multiple` leaf: `time_value × interval.to_days()`.
-/// Returns `0` for sub-day or unrecognized intervals.
+/// The whole-day sliding window for a `performed_event_multiple` leaf.
+///
+/// `explicit_datetime`(_to) takes precedence over `time_value`/`time_interval`, mirroring the single
+/// `performed_event` path ([`eviction_window`]) and the oracle's `if prop.explicit_datetime` branch.
+/// Only a relative-lower-only bound (`"-Nd"`, the dominant "in the last N days" shape) has a whole-day
+/// sliding form; every other explicit shape — and every sub-day or unrecognized interval — returns `0`,
+/// which [`pick_state_variant`] maps to [`UnsupportedVariant::HourlyDeferred`] (the leaf drops).
pub(crate) fn effective_window_days(leaf: &BehavioralLeafConfig) -> u32 {
+ if leaf.explicit_datetime.is_some() || leaf.explicit_datetime_to.is_some() {
+ return explicit_window_days(
+ leaf.explicit_datetime.as_deref(),
+ leaf.explicit_datetime_to.as_deref(),
+ );
+ }
let Some(interval) = leaf
.time_interval
.as_deref()
@@ -373,6 +384,18 @@ pub(crate) fn effective_window_days(leaf: &BehavioralLeafConfig) -> u32 {
time_value.saturating_mul(interval.to_days())
}
+/// The whole-day window for an `explicit_datetime`(_to) `performed_event_multiple` bound, reusing the
+/// single path's [`explicit_eviction_window`] classifier as the one source of truth. A sliding window
+/// is only representable for a relative-lower-only whole-day bound; every other shape (sub-day, absolute
+/// range, two-sided/relative-upper range, unparseable) has no whole-day sliding form → `0` → the leaf
+/// drops, exactly as before this fix (which returned `0` for every explicit-datetime multiple leaf).
+fn explicit_window_days(from: Option<&str>, to: Option<&str>) -> u32 {
+ match explicit_eviction_window(from, to) {
+ Ok(EvictionWindow::RelativeDays { days }) => days,
+ Ok(EvictionWindow::RelativeSeconds { .. } | EvictionWindow::Explicit { .. }) | Err(_) => 0,
+ }
+}
+
#[cfg(test)]
mod tests {
use std::sync::Arc;
@@ -911,4 +934,138 @@ mod tests {
assert_eq!(window.earliest_eviction_at_ms(1_000, UTC), i64::MAX);
}
}
+
+ /// Build a `performed_event_multiple` leaf carrying an explicit datetime range (gte 3).
+ fn explicit_multiple_leaf(from: Option<&str>, to: Option<&str>) -> BehavioralLeafConfig {
+ let mut l = leaf(BehavioralValue::PerformedEventMultiple, None, None);
+ l.operator = Some("gte".to_string());
+ l.operator_value = Some(3);
+ l.explicit_datetime = from.map(str::to_string);
+ l.explicit_datetime_to = to.map(str::to_string);
+ l.with_state_key()
+ }
+
+ #[test]
+ fn performed_event_multiple_explicit_datetime_routes_by_effective_window_days() {
+ let daily = Ok((StateVariant::BehavioralDailyBuckets, None));
+ let compressed = Ok((StateVariant::BehavioralCompressedHistory, None));
+ let deferred = Err(UnsupportedVariant::HourlyDeferred);
+ // Only a relative-lower-only whole-day bound has a sliding form. Every other explicit shape
+ // funnels to 0 → HourlyDeferred by design — the shape distinction is intentionally erased once
+ // it passes through `effective_window_days` (the discarded `UnsupportedVariant` buys no
+ // observability, so the overload is accepted, matching the time_value/interval path).
+ let cases = [
+ (
+ Some("-7d"),
+ None,
+ 7,
+ daily,
+ "relative lower -7d → 7 days → daily",
+ ),
+ (
+ Some("-180d"),
+ None,
+ 180,
+ daily,
+ "-180d → 180 days → daily (upper boundary)",
+ ),
+ (
+ Some("-1y"),
+ None,
+ 365,
+ compressed,
+ "-1y ≡ -365d → compressed",
+ ),
+ (
+ Some("-181d"),
+ None,
+ 181,
+ compressed,
+ "-181d → just over the daily boundary → compressed",
+ ),
+ (
+ Some("-2h"),
+ None,
+ 0,
+ deferred,
+ "sub-day hour → 0 → deferred",
+ ),
+ (
+ Some("-30M"),
+ None,
+ 0,
+ deferred,
+ "sub-day minute → 0 → deferred",
+ ),
+ (
+ Some("-1q"),
+ None,
+ 0,
+ deferred,
+ "unrepresentable quarter unit → 0 → deferred",
+ ),
+ (
+ Some("2026-01-01"),
+ Some("2026-12-31"),
+ 0,
+ deferred,
+ "absolute range → 0 → deferred",
+ ),
+ (
+ Some("2026-01-01"),
+ None,
+ 0,
+ deferred,
+ "absolute lower only → 0 → deferred",
+ ),
+ (
+ Some("-30d"),
+ Some("-7d"),
+ 0,
+ deferred,
+ "relative range → 0 → deferred",
+ ),
+ (
+ Some("garbage"),
+ None,
+ 0,
+ deferred,
+ "unparseable bound → 0 → deferred",
+ ),
+ ];
+ for (from, to, days, expected, why) in cases {
+ let leaf = explicit_multiple_leaf(from, to);
+ assert_eq!(effective_window_days(&leaf), days, "window_days: {why}");
+ assert_eq!(pick_state_variant(&leaf), expected, "variant: {why}");
+ }
+ }
+
+ #[test]
+ fn explicit_relative_window_days_match_the_time_value_interval_multiple_path() {
+ // A relative `explicit_datetime` and the equivalent `time_value`/`time_interval` resolve to the
+ // same window days and state variant for a `performed_event_multiple` — the same oracle query.
+ for (raw, time_value, interval) in [
+ ("-30d", 30, "day"),
+ ("-1w", 1, "week"),
+ ("-2m", 2, "month"),
+ ("-1y", 1, "year"),
+ ] {
+ let explicit = explicit_multiple_leaf(Some(raw), None);
+ let interval_path = leaf(
+ BehavioralValue::PerformedEventMultiple,
+ Some(time_value),
+ Some(interval),
+ );
+ assert_eq!(
+ effective_window_days(&explicit),
+ effective_window_days(&interval_path),
+ "{raw} vs {time_value}{interval} window_days",
+ );
+ assert_eq!(
+ pick_state_variant(&explicit),
+ pick_state_variant(&interval_path),
+ "{raw} vs {time_value}{interval} variant",
+ );
+ }
+ }
}