diff --git a/datafusion/functions/benches/datetime_expressions/date_trunc.rs b/datafusion/functions/benches/datetime_expressions/date_trunc.rs index fcee07556faa9..5e2537eca88e7 100644 --- a/datafusion/functions/benches/datetime_expressions/date_trunc.rs +++ b/datafusion/functions/benches/datetime_expressions/date_trunc.rs @@ -94,6 +94,33 @@ fn criterion_benchmark(c: &mut Criterion) { Arc::clone(&nanos), ); } + + // Timezone-aware coarse granularities truncate in local time. Sorted input + // stays within one UTC offset span for long runs; random input does not. + let random_nanos = nanosecond_timestamps(); + let mut sorted_values = random_nanos.values().to_vec(); + sorted_values.sort_unstable(); + let sorted_nanos = TimestampNanosecondArray::from(sorted_values); + for (tz, label, granularities) in [ + ( + "America/New_York", + "new_york", + &["hour", "day", "month", "year"][..], + ), + ("UTC", "utc", &["hour", "day"][..]), + ] { + for (order, array) in [("random", &random_nanos), ("sorted", &sorted_nanos)] { + let array: ArrayRef = Arc::new(array.clone().with_timezone(tz)); + for granularity in granularities { + run_benchmark( + c, + &format!("date_trunc_{granularity}_{label}_{order}_nanos_1000"), + granularity, + Arc::clone(&array), + ); + } + } + } } criterion_group!(benches, criterion_benchmark); diff --git a/datafusion/functions/src/datetime/date_trunc.rs b/datafusion/functions/src/datetime/date_trunc.rs index e1cf374efb3bb..bdc09e3d4ef68 100644 --- a/datafusion/functions/src/datetime/date_trunc.rs +++ b/datafusion/functions/src/datetime/date_trunc.rs @@ -2,12 +2,14 @@ // SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements +use std::cell::Cell; use std::num::NonZeroI64; use std::ops::{Add, Sub}; use std::str::FromStr; use std::sync::Arc; use crate::datetime::common::parse_tz; +use crate::datetime::utc_offsets::{UtcOffsetSpan, UtcOffsetSpans}; use arrow::array::temporal_conversions::{ MICROSECONDS, MILLISECONDS, NANOSECONDS, as_datetime_with_timezone, timestamp_ns_to_datetime, @@ -290,6 +292,14 @@ impl ScalarUDFImpl for DateTruncFunc { return Ok(ColumnarValue::Array(result)); } + if let (Some(tz_name), Some(tz)) = (tz_opt, parsed_tz) + && let Some(spans) = UtcOffsetSpans::for_timezone(tz_name) + { + let array = date_trunc_coarse_with_spans(array, granularity, tz, &spans)? + .with_timezone_opt(tz_opt.cloned()); + return Ok(ColumnarValue::Array(Arc::new(array))); + } + let array: PrimitiveArray = array .try_unary(|x| general_date_trunc(T::UNIT, x, parsed_tz, granularity))? .with_timezone_opt(tz_opt.cloned()); @@ -1145,6 +1155,7 @@ fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { /// Returns `None` when the truncated timestamp is no longer representable as /// nanoseconds since the epoch, which the caller reports as an out of range /// error. +#[inline] fn _date_trunc_coarse_without_tz(granularity: DatePart, value: i64) -> Option { let truncate_to = |unit: i64| value.checked_sub(value.rem_euclid(unit)); let days = || value.div_euclid(NANOS_PER_DAY); @@ -1262,6 +1273,74 @@ fn truncates_in_input_unit(granularity: DatePart, tz: Option<&Tz>) -> bool { || (tz.is_none() && granularity.is_fine_granularity_utc()) } +/// Truncates `array` to a granularity coarser than minute in the local time of +/// `tz`, with integer arithmetic between the UTC offset transitions of `tz`. +/// +/// Like [`general_date_trunc`], it returns the instant that has the truncated +/// local time and the input's UTC offset, when one exists. If the instant +/// `truncated local time - offset` lies in the input's offset span, it has that +/// local time and offset, so it is the result. Otherwise a transition falls +/// between the bucket start and the input, and the value takes the chrono path. +/// That result depends only on the offset and the truncated local time, so the +/// last one is reused, which sorted input hits for the rest of the bucket. +fn date_trunc_coarse_with_spans( + array: &PrimitiveArray, + granularity: DatePart, + tz: Tz, + spans: &UtcOffsetSpans, +) -> Result> { + let scale = match T::UNIT { + Second => NANOS_PER_SECOND, + Millisecond => NANOS_PER_MILLISECOND, + Microsecond => NANOS_PER_MICROSECOND, + Nanosecond => 1, + }; + // Sorted input stays in one span for long runs, so look it up only on a + // change. The initial span contains no instant. + let span = Cell::new(UtcOffsetSpan { + start: i64::MAX, + end: i64::MIN, + offset: 0, + }); + let last_chrono_result = Cell::new(None::<(i32, i64, i64)>); + array.try_unary(|value| { + let Some(nanos) = value.checked_mul(scale) else { + return general_date_trunc(T::UNIT, value, Some(tz), granularity); + }; + let seconds = nanos.div_euclid(NANOS_PER_SECOND); + let mut current = span.get(); + if !current.contains(seconds) { + current = spans.span(seconds); + span.set(current); + } + let offset = i64::from(current.offset) * NANOS_PER_SECOND; + let Some(local) = nanos + .checked_add(offset) + .and_then(|local| _date_trunc_coarse_without_tz(granularity, local)) + else { + return general_date_trunc(T::UNIT, value, Some(tz), granularity); + }; + if let Some(truncated) = local.checked_sub(offset) + && current.start <= truncated.div_euclid(NANOS_PER_SECOND) + { + // `truncated` is a whole number of seconds, so dividing is exact. + return Ok(truncated / scale); + } + match last_chrono_result.get() { + Some((offset, truncated_local, result)) + if offset == current.offset && truncated_local == local => + { + Ok(result) + } + _ => { + let result = general_date_trunc(T::UNIT, value, Some(tz), granularity)?; + last_chrono_result.set(Some((current.offset, local, result))); + Ok(result) + } + } + }) +} + /// The length of `granularity` in `tu`, or `None` when `granularity` is no /// coarser than `tu`, so a value in `tu` is already truncated to it. fn fine_granularity_unit(tu: TimeUnit, granularity: DatePart) -> Option { @@ -1361,11 +1440,14 @@ mod tests { use std::sync::Arc; use crate::datetime::date_trunc::{ - DateTruncFunc, NANOS_PER_MICROSECOND, date_trunc_coarse, general_date_trunc, + DateTruncFunc, NANOS_PER_MICROSECOND, NANOS_PER_SECOND, date_trunc_coarse, + date_trunc_coarse_with_spans, general_date_trunc, general_date_trunc_array_fine_granularity, parse_granularity, }; + use crate::datetime::utc_offsets::UtcOffsetSpans; use arrow::array::cast::as_primitive_array; + use arrow::array::timezone::Tz; use arrow::array::types::{ ArrowTimestampType, TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType, TimestampSecondType, @@ -1384,6 +1466,167 @@ mod tests { use datafusion_expr::sort_properties::{ExprProperties, SortProperties}; use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl}; + /// The arithmetic kernel agrees with the chrono path around every transition, + /// for input in ascending and descending order. The zones cover transitions at + /// and near midnight, a skipped day, sub-hour and sub-minute offsets and + /// closely spaced transitions; scanning every zone takes too long unoptimized. + #[test] + fn date_trunc_with_spans_matches_chrono_path() { + fn check( + zone: &str, + tz: Tz, + spans: &UtcOffsetSpans, + values: &[i64], + ) { + for granularity in [ + DatePart::Hour, + DatePart::Day, + DatePart::Week, + DatePart::Month, + DatePart::Quarter, + DatePart::Year, + ] { + let expected = values + .iter() + .map(|&value| { + general_date_trunc(T::UNIT, value, Some(tz), granularity).unwrap() + }) + .collect::>(); + for descending in [false, true] { + let mut values = values.to_vec(); + let mut expected = expected.clone(); + if descending { + values.reverse(); + expected.reverse(); + } + let array = PrimitiveArray::::from_iter_values(values.clone()); + let actual = + date_trunc_coarse_with_spans(&array, granularity, tz, spans) + .unwrap(); + if let Some(i) = + (0..values.len()).find(|&i| actual.value(i) != expected[i]) + { + panic!( + "{zone} {granularity} {:?} descending={descending}: {} truncated to {} instead of {}", + T::UNIT, + values[i], + actual.value(i), + expected[i] + ); + } + } + } + } + + for zone in [ + "UTC", + "+05:30", + "-09:30", + "+14:00", + "Africa/Cairo", + "Africa/Casablanca", + "America/Asuncion", + "America/Caracas", + "America/Goose_Bay", + "America/Havana", + "America/New_York", + "America/Santiago", + "America/Sao_Paulo", + "America/St_Johns", + "Antarctica/Troll", + "Asia/Gaza", + "Asia/Kathmandu", + "Asia/Pyongyang", + "Asia/Tehran", + "Australia/Lord_Howe", + "Europe/Dublin", + "Europe/London", + "Europe/Moscow", + "Pacific/Apia", + "Pacific/Chatham", + "Pacific/Kiritimati", + ] { + let tz: Tz = zone.parse().unwrap(); + let spans = UtcOffsetSpans::for_timezone(zone).unwrap(); + let mut seconds = spans + .transitions() + .iter() + .flat_map(|&transition| { + [-86_400, -3600, -1, 0, 1, 3600, 86_400] + .map(|delta| transition + delta) + }) + .chain([-1, 0, 1_700_000_000]) + .collect::>(); + seconds.sort_unstable(); + seconds.dedup(); + check::(zone, tz, &spans, &seconds); + let nanos = seconds + .iter() + .map(|&seconds| seconds * NANOS_PER_SECOND + 123_456_789) + .collect::>(); + check::(zone, tz, &spans, &nanos); + } + } + + #[test] + fn date_trunc_with_spans_reports_out_of_range_like_chrono_path() { + // Near `i64::MIN`, adding New York's offset overflows, while Tokyo's + // offset is added and the truncation overflows. + for (zone, granularity) in ["America/New_York", "Asia/Tokyo"] + .into_iter() + .flat_map(|zone| { + [DatePart::Hour, DatePart::Day, DatePart::Year].map(|g| (zone, g)) + }) + { + let tz: Tz = zone.parse().unwrap(); + let spans = UtcOffsetSpans::for_timezone(zone).unwrap(); + // Beyond the nanosecond range, and truncated below it. + for value in [i64::MAX / 2, i64::MIN / 1_000_000_000] { + let array = PrimitiveArray::::from(vec![value]); + assert_eq!( + date_trunc_coarse_with_spans(&array, granularity, tz, &spans) + .unwrap_err() + .strip_backtrace(), + general_date_trunc(TimeUnit::Second, value, Some(tz), granularity) + .unwrap_err() + .strip_backtrace(), + ); + } + let array = PrimitiveArray::::from(vec![ + Some(i64::MIN + 1), + None, + ]); + assert_eq!( + date_trunc_coarse_with_spans(&array, granularity, tz, &spans) + .map_err(|e| e.strip_backtrace()), + general_date_trunc( + TimeUnit::Nanosecond, + i64::MIN + 1, + Some(tz), + granularity + ) + .map(|_| array.clone()) + .map_err(|e| e.strip_backtrace()), + ); + } + } + + /// America/Creston fell back at 1944-01-01 00:01, so midnight that day is + /// ambiguous. August (UTC-6) and November (UTC-7) both truncate to it on the + /// chrono path, which picks the instant with the input's offset. + #[test] + fn date_trunc_with_spans_reuses_chrono_result_only_for_same_offset() { + let tz: Tz = "America/Creston".parse().unwrap(); + let spans = UtcOffsetSpans::for_timezone("America/Creston").unwrap(); + // 1944-08-18T19:39:14Z and 1944-11-08T00:10:20Z + let array = + PrimitiveArray::::from(vec![-800_598_046, -793_583_380]); + let actual = + date_trunc_coarse_with_spans(&array, DatePart::Year, tz, &spans).unwrap(); + // 1944-01-01T00:00-06:00 and 1944-01-01T00:00-07:00 + assert_eq!(actual.values(), &[-820_519_200, -820_515_600]); + } + #[test] fn output_ordering_respects_timestamp_timezone() { let precision_value = ScalarValue::Utf8(Some("hour".into())); diff --git a/datafusion/functions/src/datetime/mod.rs b/datafusion/functions/src/datetime/mod.rs index 8f37faa65ef42..6957714070873 100644 --- a/datafusion/functions/src/datetime/mod.rs +++ b/datafusion/functions/src/datetime/mod.rs @@ -26,6 +26,7 @@ pub mod to_local_time; pub mod to_time; pub mod to_timestamp; pub mod to_unixtime; +pub(crate) mod utc_offsets; // create UDFs make_udf_function!(current_date::CurrentDateFunc, current_date); diff --git a/datafusion/functions/src/datetime/utc_offsets.rs b/datafusion/functions/src/datetime/utc_offsets.rs new file mode 100644 index 0000000000000..56e9b114f8bbf --- /dev/null +++ b/datafusion/functions/src/datetime/utc_offsets.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! UTC offset transitions of timezones, computed once per timezone name. + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; + +use arrow::array::timezone::Tz; +use chrono::{DateTime, Offset, TimeZone}; + +/// 1800-01-01 and 2200-01-01 in epoch seconds; chrono-tz has no transitions +/// outside this window. +const TRANSITION_SCAN_START: i64 = -5_364_662_400; +const TRANSITION_SCAN_END: i64 = 7_258_118_400; +const SECONDS_PER_DAY: i64 = 86_400; + +/// The UTC offsets of a timezone over time: `offsets[i]` holds from +/// `transitions[i - 1]` (inclusive) to `transitions[i]` (exclusive), both in +/// epoch seconds, with the first and last spans unbounded. +#[derive(Debug)] +pub struct UtcOffsetSpans { + transitions: Box<[i64]>, + offsets: Box<[i32]>, +} + +/// The epoch seconds `[start, end)` over which a timezone is `offset` seconds +/// ahead of UTC. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UtcOffsetSpan { + pub start: i64, + pub end: i64, + pub offset: i32, +} + +impl UtcOffsetSpan { + /// Whether `seconds`, in epoch seconds, falls in this span. + pub fn contains(&self, seconds: i64) -> bool { + self.start <= seconds && seconds < self.end + } +} + +impl UtcOffsetSpans { + /// The spans of the timezone named `tz`, or `None` if arrow cannot parse + /// the name. + /// + /// `UTC` and fixed offsets such as `+05:30` have a single span, built on + /// every call. Other zones are scanned for transitions on the first call, + /// which takes milliseconds, and cached for the life of the process, so + /// the cache holds at most one entry per tz database name. + pub fn for_timezone(tz: &str) -> Option> { + // Arrow parses a name that starts with `+` or `-` as a fixed offset, + // and no tz database name starts with either. + if tz.eq_ignore_ascii_case("UTC") || tz.starts_with(['+', '-']) { + let offset = offset_at(&tz.parse().ok()?, 0)?; + return Some(Arc::new(Self { + transitions: Box::default(), + offsets: Box::new([offset]), + })); + } + static CACHE: LazyLock>>>> = + LazyLock::new(Default::default); + let lock = || CACHE.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(spans) = lock().get(tz) { + return spans.clone(); + } + // Scan without holding the lock. A name that fails to parse is not + // cached. + let spans = Self::scan(&tz.parse().ok()?).map(Arc::new); + lock().entry(tz.to_owned()).or_insert(spans).clone() + } + + /// The epoch seconds at which the UTC offset changes, in ascending order. + #[cfg(test)] + pub fn transitions(&self) -> &[i64] { + &self.transitions + } + + /// The span that contains `seconds`, in epoch seconds. + pub fn span(&self, seconds: i64) -> UtcOffsetSpan { + let i = self.transitions.partition_point(|&t| t <= seconds); + UtcOffsetSpan { + start: i.checked_sub(1).map_or(i64::MIN, |i| self.transitions[i]), + end: self.transitions.get(i).copied().unwrap_or(i64::MAX), + offset: self.offsets[i], + } + } + + /// Finds every UTC offset transition of `tz` between 1800 and 2200 by + /// stepping a day at a time and bisecting to the second. Steps of a day catch + /// every transition, since tz database transitions are days apart. + fn scan(tz: &Tz) -> Option { + let mut transitions = vec![]; + let mut offsets = vec![offset_at(tz, TRANSITION_SCAN_START)?]; + let mut day = TRANSITION_SCAN_START; + let mut offset = offsets[0]; + while day < TRANSITION_SCAN_END { + let next_day = day + SECONDS_PER_DAY; + if offset_at(tz, next_day)? == offset { + day = next_day; + continue; + } + let (mut before, mut after) = (day, next_day); + while after - before > 1 { + let middle = before + (after - before) / 2; + if offset_at(tz, middle)? == offset { + before = middle; + } else { + after = middle; + } + } + // Continue from the transition, so a second one in the same day is + // found too. + offset = offset_at(tz, after)?; + transitions.push(after); + offsets.push(offset); + day = after; + } + Some(Self { + transitions: transitions.into_boxed_slice(), + offsets: offsets.into_boxed_slice(), + }) + } +} + +/// The UTC offset of `tz` at `seconds`, in epoch seconds. +fn offset_at(tz: &Tz, seconds: i64) -> Option { + let utc = DateTime::from_timestamp(seconds, 0)?.naive_utc(); + Some(tz.offset_from_utc_datetime(&utc).fix().local_minus_utc()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utc_offset_spans_find_transitions() { + let spans = UtcOffsetSpans::for_timezone("America/New_York").unwrap(); + // 2024-03-10T07:00:00Z and 2024-11-03T06:00:00Z + for (transition, before, after) in [ + (1_710_054_000, -5 * 3600, -4 * 3600), + (1_730_613_600, -4 * 3600, -5 * 3600), + ] { + assert_eq!(spans.span(transition - 1).offset, before); + assert_eq!(spans.span(transition - 1).end, transition); + assert_eq!(spans.span(transition).start, transition); + assert_eq!(spans.span(transition).offset, after); + } + assert_eq!(spans.offsets.len(), spans.transitions.len() + 1); + } + + #[test] + fn utc_and_fixed_offsets_have_one_span_without_a_scan() { + for (name, offset) in [ + ("UTC", 0), + ("+00:00", 0), + ("+05:30", 19_800), + ("-0930", -34_200), + ("+14", 50_400), + ] { + let expected = UtcOffsetSpan { + start: i64::MIN, + end: i64::MAX, + offset, + }; + let spans = UtcOffsetSpans::for_timezone(name).unwrap(); + assert!(spans.transitions().is_empty(), "{name}"); + assert_eq!(spans.span(0), expected, "{name}"); + let scanned = UtcOffsetSpans::scan(&name.parse().unwrap()).unwrap(); + assert!(scanned.transitions().is_empty(), "{name}"); + assert_eq!(scanned.span(0), expected, "{name}"); + } + } + + #[test] + fn utc_offset_spans_are_cached_per_tz_database_name() { + let spans = |tz| UtcOffsetSpans::for_timezone(tz).unwrap(); + assert!(Arc::ptr_eq( + &spans("America/New_York"), + &spans("America/New_York") + )); + assert!(!Arc::ptr_eq(&spans("+05:30"), &spans("+05:30"))); + assert!(spans("Etc/GMT+5").transitions().is_empty()); + assert!(UtcOffsetSpans::for_timezone("Not/A_Zone").is_none()); + } + + #[test] + fn timezone_offsets_are_constant_outside_transition_scan_window() { + const HALF_YEAR: i64 = 183 * SECONDS_PER_DAY; + for zone in chrono_tz::TZ_VARIANTS { + let tz: Tz = zone.name().parse().unwrap(); + for step in 1..=2_000 { + assert_eq!( + offset_at(&tz, TRANSITION_SCAN_START - step * HALF_YEAR), + offset_at(&tz, TRANSITION_SCAN_START), + "{}", + zone.name() + ); + assert_eq!( + offset_at(&tz, TRANSITION_SCAN_END + step * HALF_YEAR), + offset_at(&tz, TRANSITION_SCAN_END), + "{}", + zone.name() + ); + } + } + } +}