: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
fix(flags): align datetime filter timezone with cohort evaluation (#65337)
Phil Haackf7a52a4d9775
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex e800d804f3bb..7941e7b92ea4 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3495,6 +3495,7 @@ dependencies = ["base64 0.22.1","bytes","chrono",+ "chrono-tz","clap","common-alloc","common-cache",diff --git a/rust/feature-flags/Cargo.toml b/rust/feature-flags/Cargo.tomlindex 93ea404c6a19..b4d2dc055132 100644--- a/rust/feature-flags/Cargo.toml+++ b/rust/feature-flags/Cargo.toml@@ -16,6 +16,7 @@ aws-sdk-s3 = { workspace = true, optional = true }axum = { workspace = true }axum-client-ip = { workspace = true }chrono = { workspace = true, features = ["serde"] }+chrono-tz = { workspace = true }clap = { workspace = true, optional = true }common-cookieless = { path = "../common/cookieless" }common-database = { path = "../common/database" }diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rsindex 86583438835f..bc2d1f954bfc 100644--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs@@ -8,7 +8,8 @@//!//! Deliberate differences from the live `/flags` pipeline://! - Auth is the `INTERNAL_REQUEST_TOKEN` bearer token only — no SDK token, no team lookup-//! by token.+//! by token. The team is still loaded by id (once per page) to read its timezone, so+//! naive datetime filters evaluate in the team's local time exactly like live `/flags`.//! - The handler bypasses the `/flags` request pipeline entirely, so no billing or//! flag-analytics counters are emitted, and dedicated `flags_batch_eval_*` ops metrics//! track batch traffic. The per-person matcher still emits its own evaluation metrics@@ -418,6 +419,18 @@ async fn handle_batch_flag_evaluation(.realtime_cohort_evaluation_team_ids.includes_team(request.team_id);+ // Read the team's timezone from Postgres so naive datetime filter values (IS_DATE_* and+ // relative dates) are interpreted in the team's local time, matching live `/flags`+ // evaluation and HogQL/ClickHouse cohort membership. The live path reads the same+ // `team.timezone`; this is one PK lookup per page, negligible against the per-page+ // person scan. Falls back to UTC for an unrecognized timezone string.+ let team = state+ .flag_service()+ .get_team_by_id(request.team_id)+ .await+ .map_err(BatchFlagEvaluationError::Upstream)?;+ let team_timezone = team.parsed_timezone();+let mut matched_person_uuids: Vec<Uuid> = Vec::new();let mut errors_count: u64 = 0;@@ -445,7 +458,8 @@ async fn handle_batch_flag_evaluation(.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.- .with_skip_writes(true);+ .with_skip_writes(true)+ .with_timezone(team_timezone);let evaluation = matcher.evaluate_all_feature_flags(diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rsindex 3f0ed80b2d8c..787ebcc3f34a 100644--- a/rust/feature-flags/src/api/types.rs+++ b/rust/feature-flags/src/api/types.rs@@ -5,6 +5,7 @@ use crate::flags::flag_matching_utils::match_flag_value_to_flag_filter;use crate::flags::flag_models::{FeatureFlag, FeatureFlagId};use crate::properties::property_matching::match_property;use crate::properties::property_models::OperatorType;+use chrono_tz::Tz;use serde::{de, Deserialize, Deserializer, Serialize};use serde_json::Value;use std::{collections::HashMap, fmt, str::FromStr};@@ -461,6 +462,7 @@ pub trait FromFeatureAndMatch {detailed_analysis: bool,property_values: Option<&HashMap<String, Value>>,flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,+ team_timezone: Tz,) -> Self;fn create_error(flag: &FeatureFlag, error: &FlagError, condition_index: Option<i32>) -> Self;fn get_reason_description(match_info: &FeatureFlagMatch) -> Option<String>;@@ -468,7 +470,8 @@ pub trait FromFeatureAndMatch {impl FromFeatureAndMatch for FlagDetails {fn create(flag: &FeatureFlag, flag_match: &FeatureFlagMatch) -> Self {- Self::create_with_analysis(flag, flag_match, false, None, None)+ // Timezone is only consulted for detailed analysis, which is off here.+ Self::create_with_analysis(flag, flag_match, false, None, None, Tz::UTC)}fn create_with_analysis(@@ -477,6 +480,7 @@ impl FromFeatureAndMatch for FlagDetails {detailed_analysis: bool,property_values: Option<&HashMap<String, Value>>,flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,+ team_timezone: Tz,) -> Self {FlagDetails {key: flag.key.clone(),@@ -501,6 +505,7 @@ impl FromFeatureAndMatch for FlagDetails {flag_match,property_values,flag_evaluation_results,+ team_timezone,))} else {None@@ -564,6 +569,7 @@ impl FlagDetails {flag_match: &FeatureFlagMatch,property_values: Option<&HashMap<String, Value>>,flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,+ team_timezone: Tz,) -> Vec<ConditionAnalysis> {let mut analyses = Vec::new();@@ -660,7 +666,8 @@ impl FlagDetails {let (property_matched, actual_value) = if let Some(props) = property_values {let actual = props.get(&property.key).cloned();- let matched = match_property(property, props, false).unwrap_or(false);+ let matched =+ match_property(property, props, false, team_timezone).unwrap_or(false);(matched, actual)} else {// No properties available, fall back to condition-level match@@ -1243,8 +1250,13 @@ mod tests {property_values.insert("email".to_string(), serde_json::json!("[email protected]"));// Build condition analysis- let analysis =- FlagDetails::build_condition_analysis(&flag, &flag_match, Some(&property_values), None);+ let analysis = FlagDetails::build_condition_analysis(+ &flag,+ &flag_match,+ Some(&property_values),+ None,+ chrono_tz::Tz::UTC,+ );// Verify we have analysis for both conditionsassert_eq!(analysis.len(), 2);@@ -1325,6 +1337,7 @@ mod tests {&flag_match,Some(&HashMap::new()),Some(&flag_results),+ chrono_tz::Tz::UTC,);assert_eq!(analysis.len(), 1);@@ -1356,6 +1369,7 @@ mod tests {&flag_match,Some(&HashMap::new()),Some(&flag_results),+ chrono_tz::Tz::UTC,);assert_eq!(analysis.len(), 1);@@ -1388,6 +1402,7 @@ mod tests {&flag_match,Some(&HashMap::new()),None, // empty — dependency flag 42 absent+ chrono_tz::Tz::UTC,);assert_eq!(analysis.len(), 1);diff --git a/rust/feature-flags/src/cohorts/cohort_operations.rs b/rust/feature-flags/src/cohorts/cohort_operations.rsindex a766e17fd583..f4d01f065355 100644--- a/rust/feature-flags/src/cohorts/cohort_operations.rs+++ b/rust/feature-flags/src/cohorts/cohort_operations.rs@@ -12,6 +12,7 @@ use crate::properties::property_matching::match_property;use crate::properties::property_models::OperatorType;use crate::utils::graph_utils::{DependencyGraph, DependencyProvider, DependencyType};use crate::{api::errors::FlagError, properties::property_models::PropertyFilter};+use chrono_tz::Tz;use common_database::PostgresReader;use common_types::TeamId;@@ -233,11 +234,17 @@ impl InnerCohortProperty {&self,target_properties: &HashMap<String, Value>,cohort_matches: &HashMap<CohortId, bool>,+ team_timezone: Tz,) -> Result<bool, FlagError> {match self.prop_type {CohortPropertyType::OR => {for cohort_values in &self.values {- if evaluate_cohort_values(cohort_values, target_properties, cohort_matches)? {+ if evaluate_cohort_values(+ cohort_values,+ target_properties,+ cohort_matches,+ team_timezone,+ )? {return Ok(true);}}@@ -245,7 +252,12 @@ impl InnerCohortProperty {}CohortPropertyType::AND => {for cohort_values in &self.values {- if !evaluate_cohort_values(cohort_values, target_properties, cohort_matches)? {+ if !evaluate_cohort_values(+ cohort_values,+ target_properties,+ cohort_matches,+ team_timezone,+ )? {return Ok(false);}}@@ -263,6 +275,7 @@ fn evaluate_cohort_values(values: &CohortValues,target_properties: &HashMap<String, Value>,cohort_matches: &HashMap<CohortId, bool>,+ team_timezone: Tz,) -> Result<bool, FlagError> {match values.prop_type.as_str() {"OR" => {@@ -275,7 +288,7 @@ fn evaluate_cohort_values(}} else {// Handle regular property check with negation- if evaluate_property_with_negation(filter, target_properties) {+ if evaluate_property_with_negation(filter, target_properties, team_timezone) {return Ok(true);}}@@ -296,7 +309,7 @@ fn evaluate_cohort_values(}} else {// Handle regular property check with negation- if !evaluate_property_with_negation(filter, target_properties) {+ if !evaluate_property_with_negation(filter, target_properties, team_timezone) {return Ok(false);}}@@ -314,8 +327,10 @@ fn evaluate_cohort_values(fn evaluate_property_with_negation(filter: &PropertyFilter,target_properties: &HashMap<String, Value>,+ team_timezone: Tz,) -> bool {- let property_result = match_property(filter, target_properties, false).unwrap_or(false);+ let property_result =+ match_property(filter, target_properties, false, team_timezone).unwrap_or(false);// Apply negation if specifiedif filter.negation.unwrap_or(false) {@@ -331,6 +346,7 @@ fn evaluate_single_cohort(cohort: &Cohort,target_properties: &HashMap<String, Value>,evaluation_results: &HashMap<CohortId, bool>,+ team_timezone: Tz,) -> Result<bool, FlagError> {// Get the filters for this cohortlet filters = match &cohort.filters {@@ -347,7 +363,7 @@ fn evaluate_single_cohort(// Use our evaluation method that respects OR/AND structurecohort_property.properties- .evaluate(target_properties, evaluation_results)+ .evaluate(target_properties, evaluation_results, team_timezone)}pub fn evaluate_dynamic_cohorts(@@ -355,6 +371,7 @@ pub fn evaluate_dynamic_cohorts(target_properties: &HashMap<String, Value>,cohorts: &[Cohort],static_cohort_matches: &HashMap<CohortId, bool>,+ team_timezone: Tz,) -> Result<bool, FlagError> {// First check if this is a static cohortlet initial_cohort = cohorts@@ -385,7 +402,7 @@ pub fn evaluate_dynamic_cohorts(return Ok(());}- *result = evaluate_single_cohort(cohort, target_properties, results)?;+ *result = evaluate_single_cohort(cohort, target_properties, results, team_timezone)?;Ok(())})?;@@ -792,9 +809,14 @@ mod tests {let mut static_cohort_matches = HashMap::new();static_cohort_matches.insert(10, true);- let result =- evaluate_dynamic_cohorts(20, &target_properties, &cohorts, &static_cohort_matches)- .unwrap();+ let result = evaluate_dynamic_cohorts(+ 20,+ &target_properties,+ &cohorts,+ &static_cohort_matches,+ Tz::UTC,+ )+ .unwrap();assert!(result,"Dynamic cohort should match when its static cohort dependency matches"@@ -804,9 +826,14 @@ mod tests {let mut static_cohort_matches = HashMap::new();static_cohort_matches.insert(10, false);- let result =- evaluate_dynamic_cohorts(20, &target_properties, &cohorts, &static_cohort_matches)- .unwrap();+ let result = evaluate_dynamic_cohorts(+ 20,+ &target_properties,+ &cohorts,+ &static_cohort_matches,+ Tz::UTC,+ )+ .unwrap();assert!(!result,"Dynamic cohort should not match when its static cohort dependency doesn't match"@@ -815,15 +842,84 @@ mod tests {// Test case 3: Static cohort is not in cache (defaults to false)let static_cohort_matches = HashMap::new();- let result =- evaluate_dynamic_cohorts(20, &target_properties, &cohorts, &static_cohort_matches)- .unwrap();+ let result = evaluate_dynamic_cohorts(+ 20,+ &target_properties,+ &cohorts,+ &static_cohort_matches,+ Tz::UTC,+ )+ .unwrap();assert!(!result,"Dynamic cohort should not match when static cohort is not in cache");}+ #[test]+ fn test_dynamic_cohort_datetime_filter_uses_team_timezone() {+ // A dynamic cohort with a naive datetime person-property filter must be+ // evaluated in the team timezone so Rust flag membership agrees with the+ // HogQL/ClickHouse cohort path. For a Pacific team, the filter "2024-06-01"+ // (is_date_after) resolves to 2024-06-01 07:00 UTC (PDT, UTC-7 in June).+ let cohort = Cohort {+ id: 30,+ name: Some("Datetime Cohort".to_string()),+ description: None,+ team_id: 1,+ deleted: false,+ filters: Some(json!({+ "properties": {+ "type": "OR",+ "values": [{+ "type": "OR",+ "values": [{+ "key": "joined_at",+ "type": "person",+ "value": "2024-06-01",+ "negation": false,+ "operator": "is_date_after"+ }]+ }]+ }+ })),+ query: None,+ version: None,+ pending_version: None,+ count: None,+ is_calculating: false,+ is_static: false,+ errors_calculating: 0,+ groups: json!({}),+ created_by_id: None,+ cohort_type: None,+ last_backfill_person_properties_at: None,+ };++ let cohorts = vec![cohort];+ let static_matches = HashMap::new();++ // Person joined 03:00 UTC on June 1 — after UTC midnight, but before+ // Pacific midnight (07:00 UTC). This is the offset window where the two+ // timezone interpretations disagree.+ let person = HashMap::from([("joined_at".to_string(), json!("2024-06-01T03:00:00Z"))]);++ // Pacific: the person is not strictly after the local-midnight boundary,+ // so they are not a member — matching HogQL cohort membership.+ assert!(!evaluate_dynamic_cohorts(+ 30,+ &person,+ &cohorts,+ &static_matches,+ Tz::America__Los_Angeles+ )+ .unwrap());++ // UTC (the pre-fix interpretation) would include them, proving the team+ // timezone actually changes the cohort decision in this window.+ assert!(evaluate_dynamic_cohorts(30, &person, &cohorts, &static_matches, Tz::UTC).unwrap());+ }+#[test]fn test_evaluate_dynamic_cohorts_with_negation_filters() {// Create a cohort with filters that include negation@@ -880,9 +976,14 @@ mod tests {let mut target_properties = HashMap::new();target_properties.insert("email".to_string(), json!("[email protected]"));- let result =- evaluate_dynamic_cohorts(1, &target_properties, &cohorts, &static_cohort_matches)- .unwrap();+ let result = evaluate_dynamic_cohorts(+ 1,+ &target_properties,+ &cohorts,+ &static_cohort_matches,+ Tz::UTC,+ )+ .unwrap();assert!(result,"User with @example.com email should match when not excluded"@@ -892,9 +993,14 @@ mod tests {// Should NOT match because: regex matches BUT (icontains matches -> negated to false)target_properties.insert("email".to_string(), json!("[email protected]"));- let result =- evaluate_dynamic_cohorts(1, &target_properties, &cohorts, &static_cohort_matches)- .unwrap();+ let result = evaluate_dynamic_cohorts(+ 1,+ &target_properties,+ &cohorts,+ &static_cohort_matches,+ Tz::UTC,+ )+ .unwrap();assert!(!result,"User with @example.com email should NOT match when excluded"@@ -904,18 +1010,28 @@ mod tests {// Should NOT match because: regex doesn't match (regardless of negation)target_properties.insert("email".to_string(), json!("[email protected]"));- let result =- evaluate_dynamic_cohorts(1, &target_properties, &cohorts, &static_cohort_matches)- .unwrap();+ let result = evaluate_dynamic_cohorts(+ 1,+ &target_properties,+ &cohorts,+ &static_cohort_matches,+ Tz::UTC,+ )+ .unwrap();assert!(!result, "User without @example.com email should NOT match");// Test case 4: User with excluded term but wrong domain// Should NOT match because: regex doesn't match (regardless of negation)target_properties.insert("email".to_string(), json!("[email protected]"));- let result =- evaluate_dynamic_cohorts(1, &target_properties, &cohorts, &static_cohort_matches)- .unwrap();+ let result = evaluate_dynamic_cohorts(+ 1,+ &target_properties,+ &cohorts,+ &static_cohort_matches,+ Tz::UTC,+ )+ .unwrap();assert!(!result,"User with wrong domain should NOT match regardless of exclusion"diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex 721939d2e824..09ef71dd9110 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -37,6 +37,7 @@ use crate::properties::property_models::{PropertyFilter, PropertyType};use crate::rayon_dispatcher::RayonDispatcher;use crate::utils::graph_utils::PrecomputedDependencyGraph;use anyhow::Result;+use chrono_tz::Tz;use common_metrics::{histogram, inc, timing_guard};use common_types::collections::HashMapExt;use common_types::{PersonId, TeamId};@@ -336,6 +337,10 @@ pub struct FeatureFlagMatcher {detailed_analysis: bool,/// Whether to only use person properties from request payload, ignoring database properties.only_use_override_person_properties: bool,+ /// Team timezone used to interpret naive datetime filter values (IS_DATE_* and+ /// relative dates), so flag evaluation matches HogQL/ClickHouse cohort behavior.+ /// Parsed once per request and reused across every property comparison.+ timezone: Tz,}/// Lightweight snapshot of a flag's identity fields, saved before moving@@ -403,9 +408,18 @@ impl FeatureFlagMatcher {preloaded_cohorts: None,detailed_analysis: false,only_use_override_person_properties: false,+ timezone: Tz::UTC,}}+ /// Sets the team timezone used to interpret naive datetime filter values.+ /// Defaults to UTC; production must thread the team's timezone through so flag+ /// evaluation agrees with HogQL/ClickHouse cohort membership near day boundaries.+ pub fn with_timezone(mut self, timezone: Tz) -> Self {+ self.timezone = timezone;+ self+ }+pub fn with_parallel_eval_threshold(mut self, threshold: usize) -> Self {self.parallel_eval_threshold = threshold;self@@ -739,6 +753,7 @@ impl FeatureFlagMatcher {target_properties,&cohorts,¤t_matches,+ self.timezone,)?;cohort_matches.insert(cohort_id, match_result);}@@ -1027,6 +1042,7 @@ impl FeatureFlagMatcher {true,merged_person_props.as_ref(),Some(&self.flag_evaluation_state.flag_evaluation_results),+ self.timezone,)} else {FlagDetails::create(flag, flag_match)@@ -1572,7 +1588,7 @@ impl FeatureFlagMatcher {cohort_filters.push(filter);} else {let props = property_context.resolve_for_filter(filter);- if !match_property(filter, props, false).unwrap_or(false) {+ if !match_property(filter, props, false, self.timezone).unwrap_or(false) {return Ok((false, FeatureFlagMatchReason::NoConditionMatch));}}diff --git a/rust/feature-flags/src/flags/property_filter.rs b/rust/feature-flags/src/flags/property_filter.rsindex 0f3d7a79a815..a95c4378b75a 100644--- a/rust/feature-flags/src/flags/property_filter.rs+++ b/rust/feature-flags/src/flags/property_filter.rs@@ -252,7 +252,10 @@ mod tests {regex_filter.compiled_regex,Some(CompiledRegex::InvalidPattern)));- assert_eq!(match_property(®ex_filter, &props, false), Ok(false));+ assert_eq!(+ match_property(®ex_filter, &props, false, chrono_tz::Tz::UTC),+ Ok(false)+ );let mut not_regex_filter = PropertyFilter {key: "email".to_string(),@@ -272,7 +275,10 @@ mod tests {// InvalidPattern returns Ok(false) for NotRegex too — matches existing// on-the-fly behavior where a failed compilation returns Ok(false)// regardless of operator.- assert_eq!(match_property(¬_regex_filter, &props, false), Ok(false));+ assert_eq!(+ match_property(¬_regex_filter, &props, false, chrono_tz::Tz::UTC),+ Ok(false)+ );}#[test]@@ -348,11 +354,11 @@ mod tests {compiled_regex: None,extra: Default::default(),};- let result_raw = match_property(&filter_raw, &props, false);+ let result_raw = match_property(&filter_raw, &props, false, chrono_tz::Tz::UTC);let mut filter_compiled = filter_raw.clone();filter_compiled.prepare_regex();- let result_compiled = match_property(&filter_compiled, &props, false);+ let result_compiled = match_property(&filter_compiled, &props, false, chrono_tz::Tz::UTC);assert_eq!(result_raw, result_compiled);assert_eq!(result_compiled, expected);diff --git a/rust/feature-flags/src/handler/evaluation.rs b/rust/feature-flags/src/handler/evaluation.rsindex 0afe833e7788..a866756140e9 100644--- a/rust/feature-flags/src/handler/evaluation.rs+++ b/rust/feature-flags/src/handler/evaluation.rs@@ -35,7 +35,8 @@ pub async fn evaluate_feature_flags(.with_skip_writes(context.skip_writes).with_realtime_cohort_evaluation(context.enable_realtime_cohort_evaluation).with_detailed_analysis(context.detailed_analysis)- .with_only_use_override_person_properties(context.only_use_override_person_properties);+ .with_only_use_override_person_properties(context.only_use_override_person_properties)+ .with_timezone(context.team_timezone);matcher.evaluate_all_feature_flags(diff --git a/rust/feature-flags/src/handler/flags.rs b/rust/feature-flags/src/handler/flags.rsindex de829c23dbd6..8f17cd332fce 100644--- a/rust/feature-flags/src/handler/flags.rs+++ b/rust/feature-flags/src/handler/flags.rs@@ -12,6 +12,7 @@ use crate::{utils::user_agent::{RuntimeType, UserAgentInfo},};use axum::extract::State;+use chrono_tz::Tz;use common_types::TeamId;use serde::{Deserialize, Deserializer, Serialize};use serde_json::Value;@@ -331,6 +332,7 @@ fn collect_excluded_by_tags(pub async fn evaluate_for_request(state: &State<router::State>,team_id: i32,+ team_timezone: Tz,distinct_id: String,device_id: Option<String>,filtered_flags: FeatureFlagList,@@ -361,6 +363,7 @@ pub async fn evaluate_for_request(let ctx = FeatureFlagEvaluationContext {team_id,+ team_timezone,distinct_id,device_id,feature_flags: filtered_flags,diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rsindex 0233dcee0f2b..e29a0031497d 100644--- a/rust/feature-flags/src/handler/mod.rs+++ b/rust/feature-flags/src/handler/mod.rs@@ -240,6 +240,9 @@ async fn process_request_inner(flags::evaluate_for_request(&context.state,team.id,+ // Interpret naive datetime filter values in the team timezone so flag+ // evaluation matches HogQL/ClickHouse cohort membership.+ team.parsed_timezone(),distinct_id.clone(),device_id.clone(),filtered_flags.clone(),diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rsindex bb0564b03544..0d7685d3b78f 100644--- a/rust/feature-flags/src/handler/tests.rs+++ b/rust/feature-flags/src/handler/tests.rs@@ -200,6 +200,7 @@ async fn test_evaluate_feature_flags() {let evaluation_context = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: "user123".to_string(),device_id: None,feature_flags: feature_flag_list,@@ -280,6 +281,7 @@ async fn test_evaluate_feature_flags_with_errors() {// Set up evaluation contextlet evaluation_context = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: "user123".to_string(),device_id: None,feature_flags: feature_flag_list,@@ -669,6 +671,7 @@ async fn test_evaluate_feature_flags_multiple_flags() {let evaluation_context = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: distinct_id.clone(),device_id: None,feature_flags: feature_flag_list,@@ -751,6 +754,7 @@ async fn test_evaluate_feature_flags_details() {let evaluation_context = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: distinct_id.clone(),device_id: None,feature_flags: feature_flag_list,@@ -906,6 +910,7 @@ async fn test_evaluate_feature_flags_with_overrides() {let evaluation_context = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: "user123".to_string(),device_id: None,feature_flags: feature_flag_list,@@ -983,6 +988,7 @@ async fn test_long_distinct_id() {let evaluation_context = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: long_id,device_id: None,feature_flags: feature_flag_list,@@ -1593,6 +1599,7 @@ async fn test_parallel_path_matches_sequential_results() {// Run sequential (threshold = 100, well above 4 flags)let sequential_context = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: distinct_id.clone(),device_id: None,feature_flags: seq_flag_list,@@ -1623,6 +1630,7 @@ async fn test_parallel_path_matches_sequential_results() {// Run parallel (threshold = 1, forces rayon+oneshot for any batch >= 1)let parallel_context = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: distinct_id.clone(),device_id: None,feature_flags: par_flag_list,@@ -1706,6 +1714,7 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {let provider_disabled = Arc::new(CountingCohortMembershipProvider::new());let evaluation_context_disabled = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id: distinct_id.clone(),device_id: None,feature_flags: feature_flag_list.clone(),@@ -1742,6 +1751,7 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {let provider_enabled = Arc::new(CountingCohortMembershipProvider::new());let evaluation_context_enabled = FeatureFlagEvaluationContext {team_id: team.id,+ team_timezone: chrono_tz::Tz::UTC,distinct_id,device_id: None,feature_flags: feature_flag_list,diff --git a/rust/feature-flags/src/handler/types.rs b/rust/feature-flags/src/handler/types.rsindex 8173e43a780d..7c15ecd9e2da 100644--- a/rust/feature-flags/src/handler/types.rs+++ b/rust/feature-flags/src/handler/types.rs@@ -1,5 +1,6 @@use axum::{extract::State, http::HeaderMap};use bytes::Bytes;+use chrono_tz::Tz;use serde::Serialize;use serde_json::Value;use std::{@@ -62,6 +63,9 @@ pub struct RequestPropertyOverrides {/// Represents all context required for evaluating a set of feature flags.pub struct FeatureFlagEvaluationContext {pub team_id: i32,+ /// Team timezone, used to interpret naive datetime filter values consistently+ /// with HogQL/ClickHouse cohort evaluation.+ pub team_timezone: Tz,pub distinct_id: String,pub device_id: Option<String>,pub feature_flags: FeatureFlagList,diff --git a/rust/feature-flags/src/properties/property_matching.rs b/rust/feature-flags/src/properties/property_matching.rsindex 3b68513f08c0..90a01d4e3315 100644--- a/rust/feature-flags/src/properties/property_matching.rs+++ b/rust/feature-flags/src/properties/property_matching.rs@@ -2,7 +2,8 @@ use std::collections::HashMap;use crate::properties::property_models::{CompiledRegex, OperatorType, PropertyFilter};use crate::properties::relative_date;-use chrono::{DateTime, NaiveDateTime, Utc};+use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};+use chrono_tz::Tz;use dateparser::parse as parse_date;use fancy_regex::RegexBuilder;use semver::{Version, VersionReq};@@ -55,6 +56,7 @@ pub fn match_property(property: &PropertyFilter,matching_property_values: &HashMap<String, Value>,partial_props: bool,+ team_timezone: Tz,) -> Result<bool, FlagMatchingError> {// only looks for matches where key exists in override_property_values// doesn't support operator is_not_set with partial_props@@ -390,7 +392,11 @@ pub fn match_property(Ok(requirement.matches(&parsed_value))}OperatorType::IsDateExact | OperatorType::IsDateAfter | OperatorType::IsDateBefore => {- let parsed_date = determine_parsed_date_for_property_matching(match_value);+ // Both the person value and the filter value are interpreted in the+ // team timezone (naive strings) or by their explicit offset, so the two+ // sides agree with each other and with HogQL/ClickHouse cohort evaluation.+ let parsed_date =+ determine_parsed_date_for_property_matching(match_value, team_timezone);if parsed_date.is_none() {// When value doesn't exist:@@ -399,7 +405,7 @@ pub fn match_property(}if let Some(override_value) = value.as_str() {- let override_date = match parse_date_string(override_value) {+ let override_date = match parse_date_string_in_tz(override_value, team_timezone) {Some(date) => date,None => {return Ok(false);@@ -477,36 +483,67 @@ fn is_truthy_property_value(value: &Value) -> bool {false}-fn parse_date_string(date_str: &str) -> Option<DateTime<Utc>> {- // Try relative date parsing first- if let Some(date) = relative_date::parse_relative_date(date_str) {+/// Naive wall-clock datetime formats (no embedded offset). A match here means the+/// value is interpreted in the team timezone. `%.f` is optional in chrono, so these+/// also cover the no-fractional-seconds case; both the space and `T` separators are+/// listed because chrono does not treat them as interchangeable.+const NAIVE_DATETIME_FORMATS: &[&str] = &[+ "%Y-%m-%d %H:%M:%S%.f",+ "%Y-%m-%dT%H:%M:%S%.f",+ "%Y-%m-%d %H:%M",+ "%Y-%m-%dT%H:%M",+];++/// Parses a datetime string, interpreting naive wall-clock values in+/// `team_timezone` and honoring explicit offsets as written.+///+/// Both sides of an IS_DATE_* comparison flow through here so they agree with+/// each other and with HogQL/ClickHouse cohort evaluation. HogQL wraps both the+/// stored value and the filter constant in `…(value, <team_tz>)`, so a naive+/// string like "2024-06-01" means midnight in the team timezone — not UTC.+/// Values that carry an explicit offset (a trailing `Z` or `±HH:MM`) are honored+/// as written, mirroring ClickHouse's `parseDateTime64BestEffort`, which respects+/// the embedded offset regardless of the team timezone.+fn parse_date_string_in_tz(date_str: &str, team_timezone: Tz) -> Option<DateTime<Utc>> {+ // Relative dates ("-7d", "-30d", …) are anchored to "now" in the team timezone.+ if let Some(date) = relative_date::parse_relative_date_in_tz(date_str, team_timezone) {return Some(date);}- // Try dateparser for other formats- if let Ok(date) = parse_date(date_str) {- return Some(date);+ // Explicit-offset formats carry their own timezone; honor it as-is.+ if let Ok(date) = DateTime::parse_from_rfc3339(date_str) {+ return Some(date.with_timezone(&Utc));}- // Fallback: Try parsing ISO 8601 with milliseconds (without timezone)- // This handles formats like "2025-12-19T00:00:00.000" that dateparser can't handle- if let Ok(naive_date) = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%dT%H:%M:%S%.f") {- return Some(naive_date.and_utc());+ // Bare date ("2024-06-01") is the common filter form — check it first, then the+ // forms that include a time component. All are interpreted in the team timezone.+ if let Ok(date) = NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {+ return relative_date::naive_to_utc_in_tz(date.and_hms_opt(0, 0, 0)?, team_timezone);+ }+ for fmt in NAIVE_DATETIME_FORMATS {+ if let Ok(naive) = NaiveDateTime::parse_from_str(date_str, fmt) {+ return relative_date::naive_to_utc_in_tz(naive, team_timezone);+ }}- None+ // Fallback for any exotic format the explicit list misses; assumes UTC for+ // naive input — preferable to failing the match outright.+ parse_date(date_str).ok()}-fn determine_parsed_date_for_property_matching(value: Option<&Value>) -> Option<DateTime<Utc>> {+fn determine_parsed_date_for_property_matching(+ value: Option<&Value>,+ team_timezone: Tz,+) -> Option<DateTime<Utc>> {let value = value?;if let Some(date_str) = value.as_str() {- // First try parsing as a float timestamp+ // First try parsing as a float timestamp (an unambiguous epoch instant).if let Ok(num) = date_str.parse::<f64>() {return parse_float_timestamp(num);}- // Then try relative date parsing- return parse_date_string(date_str);+ // Otherwise interpret the string in the team timezone, like the filter side.+ return parse_date_string_in_tz(date_str, team_timezone);}if let Some(num) = value.as_number() {@@ -536,6 +573,16 @@ mod test_match_properties {use serde_json::json;use test_case::test_case;+ /// UTC-defaulting wrapper so timezone-agnostic tests stay terse. Date-specific+ /// tests call `super::match_property` directly with the team timezone they need.+ fn match_property(+ property: &PropertyFilter,+ matching_property_values: &HashMap<String, Value>,+ partial_props: bool,+ ) -> Result<bool, FlagMatchingError> {+ super::match_property(property, matching_property_values, partial_props, Tz::UTC)+ }+#[test]fn test_match_properties_exact_with_partial_props() {let property_a = PropertyFilter {@@ -1969,9 +2016,11 @@ mod test_match_properties {.with_timezone(&Utc);let timestamp_number = 1836277747;let timestamp_string = timestamp_number.to_string();- let date = determine_parsed_date_for_property_matching(Some(&json!(timestamp_number)));+ let date =+ determine_parsed_date_for_property_matching(Some(&json!(timestamp_number)), Tz::UTC);assert_eq!(date, Some(expected_date));- let date = determine_parsed_date_for_property_matching(Some(&json!(timestamp_string)));+ let date =+ determine_parsed_date_for_property_matching(Some(&json!(timestamp_string)), Tz::UTC);assert_eq!(date, Some(expected_date));}@@ -1981,20 +2030,23 @@ mod test_match_properties {.unwrap().with_timezone(&Utc);let timestamp_number = 1836277747.86753;- let date = determine_parsed_date_for_property_matching(Some(&json!(timestamp_number)));+ let date =+ determine_parsed_date_for_property_matching(Some(&json!(timestamp_number)), Tz::UTC);assert_eq!(date, Some(expected_date));let timestamp_string = "1836277747.86753";- let date = determine_parsed_date_for_property_matching(Some(&json!(timestamp_string)));+ let date =+ determine_parsed_date_for_property_matching(Some(&json!(timestamp_string)), Tz::UTC);assert_eq!(date, Some(expected_date));}#[test]fn test_parse_iso8601_with_milliseconds_no_timezone() {- // Test parsing ISO 8601 format with milliseconds but no timezone- // This format is generated by some systems and should be parsed as UTC+ // Test parsing ISO 8601 format with milliseconds but no timezone. A naive+ // value like this is interpreted in the team timezone; this test passes+ // Tz::UTC, so the result lands at UTC midnight.let date_string = "2025-12-19T00:00:00.000";- let date = parse_date_string(date_string);+ let date = parse_date_string_in_tz(date_string, Tz::UTC);assert!(date.is_some(),"Should be able to parse ISO 8601 with milliseconds"@@ -2012,13 +2064,13 @@ mod test_match_properties {#[test]fn test_parse_iso8601_with_variable_millisecond_precision() {// Test 1 digit milliseconds- assert!(parse_date_string("2025-12-19T00:00:00.5").is_some());+ assert!(parse_date_string_in_tz("2025-12-19T00:00:00.5", Tz::UTC).is_some());// Test 2 digit milliseconds- assert!(parse_date_string("2025-12-19T00:00:00.12").is_some());+ assert!(parse_date_string_in_tz("2025-12-19T00:00:00.12", Tz::UTC).is_some());// Test 3 digit milliseconds (existing case)- assert!(parse_date_string("2025-12-19T00:00:00.123").is_some());+ assert!(parse_date_string_in_tz("2025-12-19T00:00:00.123", Tz::UTC).is_some());}#[test]@@ -3544,4 +3596,179 @@ mod test_match_properties {).expect("expected match to exist"));}++ // Timezone parity tests+ //+ // These prove the Rust matcher interprets a naive datetime filter (the+ // right-hand side) in the team timezone — exactly as HogQL/ClickHouse cohort+ // evaluation does. HogQL lowers a naive IS_DATE_* constant to+ // `toDateTime(value, <team_tz>)`, so for an `America/Los_Angeles` team the+ // filter "2024-06-01" means 2024-06-01 00:00 Pacific = 2024-06-01 07:00 UTC+ // (PDT, UTC-7 in June), not 2024-06-01 00:00 UTC.+ //+ // The person value (left-hand side) is supplied as an unambiguous UTC instant+ // (a `Z`-suffixed ISO string or an epoch), so both engines agree on it and the+ // only thing under test is the right-hand-side interpretation. Each case also+ // asserts the pre-fix UTC interpretation produced a different decision in the+ // offset window straddling local midnight.++ const PACIFIC: Tz = Tz::America__Los_Angeles;++ fn date_filter(value: &str, operator: OperatorType) -> PropertyFilter {+ PropertyFilter {+ key: "joined_at".to_string(),+ value: Some(json!(value)),+ operator: Some(operator),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }+ }++ fn match_date(person_value: Value, filter: &PropertyFilter, tz: Tz) -> bool {+ super::match_property(+ filter,+ &HashMap::from([("joined_at".to_string(), person_value)]),+ true,+ tz,+ )+ .expect("expected match to exist")+ }++ #[test_case("2024-06-01T03:00:00Z", false; "person before pacific midnight does not match")]+ #[test_case("2024-06-01T08:00:00Z", true; "person after pacific midnight matches")]+ fn test_is_date_after_interpreted_in_team_tz(person_iso: &str, expected_pacific: bool) {+ // Filter "2024-06-01" after-midnight resolves to 07:00 UTC for a Pacific team.+ let filter = date_filter("2024-06-01", OperatorType::IsDateAfter);+ assert_eq!(+ match_date(json!(person_iso), &filter, PACIFIC),+ expected_pacific+ );++ // The same person value at 03:00 UTC sits inside the offset window: it is+ // "after" UTC midnight but "before" Pacific midnight, so the pre-fix UTC+ // interpretation disagrees with the team-tz one.+ if person_iso == "2024-06-01T03:00:00Z" {+ assert!(match_date(json!(person_iso), &filter, Tz::UTC));+ assert_ne!(+ match_date(json!(person_iso), &filter, PACIFIC),+ match_date(json!(person_iso), &filter, Tz::UTC)+ );+ }+ }++ #[test_case("2024-06-01T03:00:00Z", true; "person before pacific midnight is before")]+ #[test_case("2024-06-01T08:00:00Z", false; "person after pacific midnight is not before")]+ fn test_is_date_before_interpreted_in_team_tz(person_iso: &str, expected_pacific: bool) {+ let filter = date_filter("2024-06-01", OperatorType::IsDateBefore);+ assert_eq!(+ match_date(json!(person_iso), &filter, PACIFIC),+ expected_pacific+ );++ // Pre-fix UTC interpretation flips the decision inside the offset window.+ if person_iso == "2024-06-01T03:00:00Z" {+ assert!(!match_date(json!(person_iso), &filter, Tz::UTC));+ }+ }++ #[test]+ fn test_is_date_exact_interpreted_in_team_tz() {+ // "2024-06-01" == 2024-06-01 07:00 UTC for a Pacific team.+ let filter = date_filter("2024-06-01", OperatorType::IsDateExact);++ assert!(match_date(json!("2024-06-01T07:00:00Z"), &filter, PACIFIC));+ assert!(!match_date(json!("2024-06-01T00:00:00Z"), &filter, PACIFIC));++ // Under UTC the equality lands on 00:00Z instead — the opposite decision.+ assert!(match_date(json!("2024-06-01T00:00:00Z"), &filter, Tz::UTC));+ assert!(!match_date(json!("2024-06-01T07:00:00Z"), &filter, Tz::UTC));+ }++ #[test]+ fn test_is_date_after_with_explicit_offset_filter_ignores_team_tz() {+ // A filter value carrying an explicit offset is honored as written, so the+ // team timezone must not shift it. "2024-06-01T00:00:00Z" is 00:00 UTC+ // regardless of the team timezone.+ let filter = date_filter("2024-06-01T00:00:00Z", OperatorType::IsDateAfter);+ let person = json!("2024-06-01T03:00:00Z");+ assert!(match_date(person.clone(), &filter, PACIFIC));+ assert_eq!(+ match_date(person.clone(), &filter, PACIFIC),+ match_date(person, &filter, Tz::UTC)+ );+ }++ #[test]+ fn test_is_date_after_with_epoch_person_value() {+ // Epoch person values are unambiguous instants; only the naive filter is+ // reinterpreted. 1717225200 = 2024-06-01 07:00:00 UTC, exactly Pacific+ // midnight, so it is not strictly after the "2024-06-01" boundary.+ let filter = date_filter("2024-06-01", OperatorType::IsDateAfter);+ assert!(!match_date(json!(1717225200_i64), &filter, PACIFIC));+ // One second later is after the boundary.+ assert!(match_date(json!(1717225201_i64), &filter, PACIFIC));+ }++ #[test]+ fn test_relative_date_filter_evaluates_in_team_tz_without_panicking() {+ // Relative dates anchor to "now" in the team timezone. The exact instant+ // depends on wall-clock time, so use a comfortable margin: a person who+ // joined 30 days ago is "before -7d", one who joined now is not. This+ // exercises the non-UTC relative path end to end (the deterministic+ // team-tz anchoring is covered in relative_date.rs).+ //+ // Use a non-DST zone (Tokyo, UTC+9 year-round) so "now - 7d" can never land+ // in a spring-forward wall-clock gap. That keeps the test deterministic+ // every day of the year — no skip path that would silently drop coverage.+ const TOKYO: Tz = Tz::Asia__Tokyo;+ let filter = date_filter("-7d", OperatorType::IsDateBefore);++ let thirty_days_ago = (Utc::now() - chrono::Duration::days(30)).to_rfc3339();+ let now = Utc::now().to_rfc3339();+ assert!(match_date(json!(thirty_days_ago), &filter, TOKYO));+ assert!(!match_date(json!(now), &filter, TOKYO));+ }++ #[test]+ fn test_naive_person_value_interpreted_in_team_tz() {+ // A naive person value is also read in the team timezone (matching HogQL,+ // which wraps both sides in the team tz). Against a fixed absolute filter+ // this changes the decision: a naive person clock of 08:00 is 15:00 UTC in+ // Pacific (after the 14:00Z filter) but 08:00 UTC if misread as UTC (before+ // it). This is the half of the fix that keeps the person side consistent.+ let filter = date_filter("2024-06-01T14:00:00Z", OperatorType::IsDateAfter);+ let person = json!("2024-06-01 08:00:00"); // naive wall clock, no offset++ assert!(match_date(person.clone(), &filter, PACIFIC));+ assert!(!match_date(person, &filter, Tz::UTC));+ }++ #[test]+ fn test_naive_person_and_naive_filter_agree_across_timezones() {+ // When both the person value and the filter are naive, they receive the+ // same team-tz shift, so the comparison reduces to a wall-clock comparison+ // that lands the same way in every timezone — matching HogQL (which reads+ // both sides in team tz) and never diverging at the day boundary. This is+ // the case a filter-only fix would have regressed.+ let after = date_filter("2024-06-01", OperatorType::IsDateAfter);+ let before = date_filter("2024-06-01", OperatorType::IsDateBefore);+ let person = json!("2024-06-01 03:00:00"); // naive: 03:00 is after midnight++ assert!(match_date(person.clone(), &after, PACIFIC));+ assert!(!match_date(person.clone(), &before, PACIFIC));++ // Identical decision under UTC — both sides move together, so naive+naive+ // has no day-boundary divergence between the two engines.+ assert_eq!(+ match_date(person.clone(), &after, PACIFIC),+ match_date(person.clone(), &after, Tz::UTC)+ );+ assert_eq!(+ match_date(person.clone(), &before, PACIFIC),+ match_date(person, &before, Tz::UTC)+ );+ }}diff --git a/rust/feature-flags/src/properties/relative_date.rs b/rust/feature-flags/src/properties/relative_date.rsindex b54ce2de422c..10cdc38f5b0c 100644--- a/rust/feature-flags/src/properties/relative_date.rs+++ b/rust/feature-flags/src/properties/relative_date.rs@@ -1,4 +1,5 @@-use chrono::{DateTime, Datelike, Duration, TimeZone, Timelike, Utc};+use chrono::{DateTime, Datelike, Duration, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Utc};+use chrono_tz::Tz;use once_cell::sync::Lazy;use regex::Regex;@@ -7,8 +8,11 @@ static RELATIVE_DATE_REGEX: Lazy<Regex> = Lazy::new(|| {Regex::new(r"^-?(?P<number>[0-9]+)(?P<interval>[hdwmy])$").expect("Invalid regex pattern")});-/// Parse a relative date string like "-3d", "3d", "-3h", etc.-/// Returns None if the string doesn't match the expected format or if the number is too large.+/// Parse a relative date string like "-3d", "3d", "-3h", etc., anchored to the+/// current UTC time.+///+/// Returns None if the string doesn't match the expected format or if the number+/// is too large.////// This implementation matches Python's behavior using relativedelta:/// - Hours and days use fixed durations@@ -25,11 +29,52 @@ static RELATIVE_DATE_REGEX: Lazy<Regex> = Lazy::new(|| {/// assert!(three_days_ago < now);/// ```pub fn parse_relative_date(date_str: &str) -> Option<DateTime<Utc>> {- parse_relative_date_with_now(date_str, Utc::now())+ // The wall clock in UTC is the same as the absolute instant, so the naive+ // arithmetic below reproduces the previous UTC-anchored behavior exactly.+ parse_relative_date_naive(date_str, Utc::now().naive_utc()).map(|naive| naive.and_utc())+}++/// Parse a relative date string anchored to the current wall clock in `tz`,+/// returning the resulting instant in UTC.+///+/// This mirrors HogQL's `relative_date_parse(value, team.timezone_info)`: the+/// relativedelta arithmetic runs against the team-timezone wall clock, and the+/// resulting wall clock is then interpreted back in the team timezone. Keeping+/// the subtraction on the naive wall clock (rather than on an absolute UTC+/// instant) is what makes "in the last N days" land on the same local day+/// boundary in both engines.+pub fn parse_relative_date_in_tz(date_str: &str, tz: Tz) -> Option<DateTime<Utc>> {+ // Cheap reject for the common case (absolute date strings) before reading the+ // clock and localizing — that work is wasted whenever the regex won't match.+ if !RELATIVE_DATE_REGEX.is_match(date_str) {+ return None;+ }+ let now_local = Utc::now().with_timezone(&tz).naive_local();+ let result = parse_relative_date_naive(date_str, now_local)?;+ naive_to_utc_in_tz(result, tz)}-/// Internal function that takes a specific "now" time for testing-fn parse_relative_date_with_now(date_str: &str, now: DateTime<Utc>) -> Option<DateTime<Utc>> {+/// Interpret a naive wall-clock datetime as a moment in `tz`, returning UTC.+///+/// On a DST fall-back overlap (the same wall clock occurs twice) we pick the+/// earliest instant; on a spring-forward gap (the wall clock never occurs) we+/// return None. The gap case is a ~1h/year edge well outside the day-boundary+/// window this fix targets, and a missing match there is preferable to a silently+/// shifted one.+pub(crate) fn naive_to_utc_in_tz(naive: NaiveDateTime, tz: Tz) -> Option<DateTime<Utc>> {+ match tz.from_local_datetime(&naive) {+ LocalResult::Single(dt) => Some(dt.with_timezone(&Utc)),+ LocalResult::Ambiguous(earliest, _latest) => Some(earliest.with_timezone(&Utc)),+ LocalResult::None => None,+ }+}++/// Apply the relativedelta-style subtraction purely on a naive wall clock.+///+/// All arithmetic is timezone-agnostic here; callers decide how to anchor `now`+/// and how to interpret the result. Time-of-day (including sub-second precision)+/// is preserved across calendar month/year shifts.+fn parse_relative_date_naive(date_str: &str, now: NaiveDateTime) -> Option<NaiveDateTime> {let captures = RELATIVE_DATE_REGEX.captures(date_str)?;let number: i64 = captures.name("number")?.as_str().parse().ok()?;@@ -60,33 +105,10 @@ fn parse_relative_date_with_now(date_str: &str, now: DateTime<Utc>) -> Option<Da(year, month - 1)};- // Get the last day of the previous month- let last_day = if prev_month == 2 {- if prev_year % 4 == 0 && (prev_year % 100 != 0 || prev_year % 400 == 0) {- 29 // Leap year- } else {- 28 // Non-leap year- }- } else if [4, 6, 9, 11].contains(&prev_month) {- 30- } else {- 31- };-// Use the minimum of the original day and the last day of the previous month- let new_day = day.min(last_day);- result = Utc- .with_ymd_and_hms(- prev_year,- prev_month,- new_day,- result.hour(),- result.minute(),- result.second(),- )- .unwrap()- .with_nanosecond(result.nanosecond())- .unwrap();+ let new_day = day.min(last_day_of_month(prev_year, prev_month));+ result = NaiveDate::from_ymd_opt(prev_year, prev_month, new_day)?+ .and_time(result.time());}Some(result)}@@ -98,29 +120,14 @@ fn parse_relative_date_with_now(date_str: &str, now: DateTime<Utc>) -> Option<Dalet month = result.month();let day = result.day();- // Handle February 29 in leap years- let new_day = if month == 2 && day == 29 {- if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {- 29 // Leap year- } else {- 28 // Non-leap year- }+ // Handle February 29 in non-leap target years+ let new_day = if month == 2 {+ day.min(last_day_of_month(year, month))} else {day};- result = Utc- .with_ymd_and_hms(- year,- month,- new_day,- result.hour(),- result.minute(),- result.second(),- )- .unwrap()- .with_nanosecond(result.nanosecond())- .unwrap();+ result = NaiveDate::from_ymd_opt(year, month, new_day)?.and_time(result.time());}Some(result)}@@ -128,15 +135,32 @@ fn parse_relative_date_with_now(date_str: &str, now: DateTime<Utc>) -> Option<Da}}+/// Last calendar day of the given month, accounting for leap years.+fn last_day_of_month(year: i32, month: u32) -> u32 {+ if month == 2 {+ if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {+ 29+ } else {+ 28+ }+ } else if [4, 6, 9, 11].contains(&month) {+ 30+ } else {+ 31+ }+}+#[cfg(test)]mod tests {use super::*;- use chrono::{TimeZone, Utc};+ use chrono::{TimeZone, Timelike, Utc};use test_case::test_case;- // Helper function to parse relative date with a fixed "now" time+ // Helper function to parse relative date with a fixed "now" time. The naive+ // UTC wall clock equals the absolute instant, so this exercises the same+ // arithmetic the UTC-anchored `parse_relative_date` uses.fn parse_relative_date_fixed(date_str: &str, now: DateTime<Utc>) -> Option<DateTime<Utc>> {- parse_relative_date_with_now(date_str, now)+ parse_relative_date_naive(date_str, now.naive_utc()).map(|naive| naive.and_utc())}#[test_case("-3d" => true; "negative days")]@@ -500,4 +524,64 @@ mod tests {assert!(parse_relative_date_fixed("9999m", now).is_some());assert!(parse_relative_date_fixed("9999y", now).is_some());}++ #[test]+ fn test_naive_to_utc_in_tz_pacific_offset() {+ // June → PDT (UTC-7). A wall clock of 2024-06-03 02:00 in Pacific is+ // 2024-06-03 09:00 UTC.+ let naive = NaiveDate::from_ymd_opt(2024, 6, 3)+ .unwrap()+ .and_hms_opt(2, 0, 0)+ .unwrap();+ let utc = naive_to_utc_in_tz(naive, Tz::America__Los_Angeles).unwrap();+ assert_eq!(utc, Utc.with_ymd_and_hms(2024, 6, 3, 9, 0, 0).unwrap());+ }++ #[test]+ fn test_relative_date_naive_anchored_in_tz_matches_hogql() {+ // Mirrors HogQL's relative_date_parse(value, team.timezone_info): the+ // relativedelta runs on the team-timezone wall clock, then the result is+ // interpreted back in the team timezone. Anchoring "now" to 2024-06-10+ // 02:00 Pacific, "-7d" lands on 2024-06-03 02:00 Pacific = 09:00 UTC.+ let now_pacific_wall = NaiveDate::from_ymd_opt(2024, 6, 10)+ .unwrap()+ .and_hms_opt(2, 0, 0)+ .unwrap();+ let result = parse_relative_date_naive("-7d", now_pacific_wall).unwrap();+ let utc = naive_to_utc_in_tz(result, Tz::America__Los_Angeles).unwrap();+ assert_eq!(utc, Utc.with_ymd_and_hms(2024, 6, 3, 9, 0, 0).unwrap());++ // The same wall clock interpreted as UTC (the pre-fix behavior) lands 7h+ // earlier, which is exactly the day-boundary divergence this fix removes.+ let utc_anchored = parse_relative_date_naive("-7d", now_pacific_wall)+ .unwrap()+ .and_utc();+ assert_eq!(+ utc_anchored,+ Utc.with_ymd_and_hms(2024, 6, 3, 2, 0, 0).unwrap()+ );+ assert_ne!(utc, utc_anchored);+ }++ #[test]+ fn test_naive_to_utc_in_tz_fall_back_picks_earliest() {+ // On 2024-11-03 the Pacific clock falls back 02:00 PDT → 01:00 PST, so 01:30+ // occurs twice. We pick the earliest instant (PDT, UTC-7 = 08:30 UTC).+ let naive = NaiveDate::from_ymd_opt(2024, 11, 3)+ .unwrap()+ .and_hms_opt(1, 30, 0)+ .unwrap();+ let utc = naive_to_utc_in_tz(naive, Tz::America__Los_Angeles).unwrap();+ assert_eq!(utc, Utc.with_ymd_and_hms(2024, 11, 3, 8, 30, 0).unwrap());+ }++ #[test]+ fn test_naive_to_utc_in_tz_spring_forward_gap_is_none() {+ // On 2024-03-10 the Pacific clock jumps 02:00 → 03:00, so 02:30 never occurs.+ let naive = NaiveDate::from_ymd_opt(2024, 3, 10)+ .unwrap()+ .and_hms_opt(2, 30, 0)+ .unwrap();+ assert!(naive_to_utc_in_tz(naive, Tz::America__Los_Angeles).is_none());+ }}diff --git a/rust/feature-flags/src/team/team_operations.rs b/rust/feature-flags/src/team/team_operations.rsindex 4b44e6a763de..26692524d62f 100644--- a/rust/feature-flags/src/team/team_operations.rs+++ b/rust/feature-flags/src/team/team_operations.rs@@ -2,6 +2,7 @@ use crate::{api::errors::FlagError, database::get_connection_with_metrics, team::team_models::Team,};use common_database::PostgresReader;+use tracing::warn;/// SQL fragment for selecting all Team columnsconst TEAM_COLUMNS: &str = "@@ -46,6 +47,17 @@ const TEAM_COLUMNS: &str = "";impl Team {+ /// Parses the team's stored timezone string into a `chrono_tz::Tz`, falling back to+ /// UTC (with a warning) for an unrecognized value. Every flag-evaluation path that+ /// interprets naive datetime filter values in the team's local time goes through here,+ /// so the fallback policy and warning live in one place.+ pub fn parsed_timezone(&self) -> chrono_tz::Tz {+ self.timezone.parse().unwrap_or_else(|_| {+ warn!(team_id = self.id, timezone = %self.timezone, "unrecognized team timezone, falling back to UTC for datetime flag evaluation");+ chrono_tz::Tz::UTC+ })+ }+pub async fn from_pg(client: PostgresReader, token: &str) -> Result<Team, FlagError> {let mut conn =get_connection_with_metrics(&client, "non_persons_reader", "fetch_team").await?;diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex dab4cf050432..0c3f11fab467 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -918,6 +918,20 @@ pub async fn update_team_autocapture_exceptions(Ok(())}+pub async fn update_team_timezone(+ client: Arc<dyn Client + Send + Sync>,+ team_id: i32,+ timezone: &str,+) -> Result<(), Error> {+ let mut conn = client.get_connection().await?;+ sqlx::query("UPDATE posthog_team SET timezone = $1 WHERE id = $2")+ .bind(timezone)+ .bind(team_id)+ .execute(&mut *conn)+ .await?;+ Ok(())+}+/// Build a `FeatureFlagList` with proper `EvaluationMetadata` from a list of flags.////// Scans each flag's filters for `PropertyType::Flag` dependencies and produces@@ -1288,6 +1302,10 @@ impl TestContext {update_team_autocapture_exceptions(self.non_persons_writer.clone(), team_id, enabled).await}+ pub async fn update_team_timezone(&self, team_id: i32, timezone: &str) -> Result<(), Error> {+ update_team_timezone(self.non_persons_writer.clone(), team_id, timezone).await+ }+pub async fn get_person_id_by_distinct_id(&self,team_id: i32,diff --git a/rust/feature-flags/tests/test_batch_flag_evaluation.rs b/rust/feature-flags/tests/test_batch_flag_evaluation.rsindex be90db1dc27c..a2c1c2c7ba4b 100644--- a/rust/feature-flags/tests/test_batch_flag_evaluation.rs+++ b/rust/feature-flags/tests/test_batch_flag_evaluation.rs@@ -383,6 +383,81 @@ async fn test_property_filter_selects_matching_persons() -> Result<()> {Ok(())}+#[tokio::test]+async fn test_datetime_filter_uses_team_timezone_not_utc() -> Result<()> {+ // Batch eval must interpret naive datetime person values in the team's timezone, the+ // same as live `/flags` evaluation and HogQL/ClickHouse cohort membership. The handler+ // reads `team.timezone` from Postgres server-side; the Django caller sends no timezone.+ //+ // Phoenix is UTC-7 year-round (no DST), so the arithmetic is unambiguous. The filter+ // pins an explicit-UTC instant (12:00Z), while the person value is a naive wall-clock+ // time interpreted in the team timezone:+ // - In America/Phoenix, "2024-06-01 08:00:00" is 2024-06-01 15:00 UTC → after 12:00Z → matches.+ // - Under a wrong UTC fallback it would be 08:00 UTC → not after 12:00Z → would NOT match.+ // So this person is matched only if the team timezone is applied.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ context+ .update_team_timezone(team.id, "America/Phoenix")+ .await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "date-flag",+ json!({+ "groups": [{+ "properties": [{+ "key": "signup_date",+ "type": "person",+ "value": "2024-06-01T12:00:00Z",+ "operator": "is_date_after",+ }],+ "rollout_percentage": 100,+ }],+ }),+ )),+ )+ .await?;++ for (distinct_id, signup_date) in [+ // 15:00 UTC in Phoenix → after the filter only because the team tz is applied.+ ("tz_dependent_match", "2024-06-01 08:00:00"),+ // Well before the filter under any timezone → never matches (selection control).+ ("clearly_before", "2020-01-01 00:00:00"),+ ] {+ context+ .insert_person(+ team.id,+ distinct_id.to_string(),+ Some(json!({ "signup_date": signup_date })),+ )+ .await?;+ }++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "date-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ let matched = context+ .get_person_uuid_by_distinct_id(team.id, "tz_dependent_match")+ .await?;++ assert_eq!(matched_uuids(&json_response), vec![matched]);+ assert_eq!(json_response["errors_count"], json!(0));+ assert_eq!(json_response["next_cursor"], Value::Null);++ Ok(())+}+#[tokio::test]async fn test_rollout_percentage_bucketing_matches_live_hash() -> Result<()> {// Rollout bucketing must use the same `_hash(key, identifier)` as live evaluation.