From f1fa295cf063bf68a89d9c76bf60686e039faa0f Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Tue, 1 Dec 2026 10:36:14 +0800 Subject: [PATCH 1/3] perf: truncate timezone-aware timestamps with integer arithmetic in `date_trunc` For a timezone-aware timestamp, `date_trunc` to `hour` or a coarser granularity converted every value to a chrono `DateTime`, truncated it field by field and resolved the truncated local time back to UTC, at 100 to 170 ns per value. The result depends only on the truncated local time and the input's UTC offset, and it is `truncated local time - offset` whenever that instant still has the offset. So find the UTC offset transitions of each zone once, between 1800 and 2200 by daily steps and bisection, cache them per timezone name, and truncate with integer arithmetic. A value whose bucket starts before a transition, such as a July value truncated to the year in New York, still takes the chrono path, which reuses its last result for sorted input. --- .../datetime_expressions/date_trunc.rs | 27 ++ .../functions/src/datetime/date_trunc.rs | 378 +++++++++++++++++- 2 files changed, 402 insertions(+), 3 deletions(-) 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..6578698d63c7b 100644 --- a/datafusion/functions/src/datetime/date_trunc.rs +++ b/datafusion/functions/src/datetime/date_trunc.rs @@ -2,10 +2,12 @@ // 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::collections::HashMap; use std::num::NonZeroI64; use std::ops::{Add, Sub}; use std::str::FromStr; -use std::sync::Arc; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; use crate::datetime::common::parse_tz; use arrow::array::temporal_conversions::{ @@ -41,7 +43,7 @@ use datafusion_macros::user_doc; use chrono::{ DateTime, Datelike, Duration, LocalResult, Months, NaiveDate, NaiveDateTime, Offset, - TimeDelta, Timelike, Weekday, + TimeDelta, TimeZone, Timelike, Weekday, }; fn parse_granularity(value: &str) -> Result { @@ -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) = cached_utc_offset_spans(tz_name, tz) + { + 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,169 @@ 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. + let span = Cell::new(UtcOffsetSpan::EMPTY); + 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 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)] +struct UtcOffsetSpans { + transitions: Vec, + offsets: Vec, +} + +/// The epoch seconds `[start, end)` over which a timezone has `offset`. +#[derive(Clone, Copy, Debug, PartialEq)] +struct UtcOffsetSpan { + start: i64, + end: i64, + offset: i32, +} + +impl UtcOffsetSpan { + const EMPTY: Self = Self { + start: i64::MAX, + end: i64::MIN, + offset: 0, + }; + + fn contains(&self, seconds: i64) -> bool { + self.start <= seconds && seconds < self.end + } +} + +impl UtcOffsetSpans { + /// 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 new(tz: &Tz) -> Option { + let offset_at = |seconds: i64| { + let utc = DateTime::from_timestamp(seconds, 0)?.naive_utc(); + Some(tz.offset_from_utc_datetime(&utc).fix().local_minus_utc()) + }; + let mut transitions = vec![]; + let mut offsets = vec![offset_at(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(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(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(after)?; + transitions.push(after); + offsets.push(offset); + day = after; + } + Some(Self { + transitions, + offsets, + }) + } + + /// The span that contains `seconds`. + 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], + } + } +} + +/// [`UtcOffsetSpans`] of `tz`, computed once per timezone name. +fn cached_utc_offset_spans(tz_name: &str, tz: Tz) -> Option> { + static CACHE: LazyLock>>>> = + LazyLock::new(Default::default); + let lock = || CACHE.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(spans) = lock().get(tz_name) { + return spans.clone(); + } + // Scan without holding the lock, which takes milliseconds. + let spans = UtcOffsetSpans::new(&tz).map(Arc::new); + lock().entry(tz_name.to_owned()).or_insert(spans).clone() +} + +/// 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 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 +1535,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, SECONDS_PER_DAY, + TRANSITION_SCAN_END, TRANSITION_SCAN_START, UtcOffsetSpan, UtcOffsetSpans, + date_trunc_coarse, date_trunc_coarse_with_spans, general_date_trunc, general_date_trunc_array_fine_granularity, parse_granularity, }; use arrow::array::cast::as_primitive_array; + use arrow::array::timezone::Tz; use arrow::array::types::{ ArrowTimestampType, TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType, TimestampSecondType, @@ -1384,6 +1561,201 @@ mod tests { use datafusion_expr::sort_properties::{ExprProperties, SortProperties}; use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl}; + use chrono::{DateTime, Offset, TimeZone}; + + fn offset_at(tz: &Tz, seconds: i64) -> i32 { + let utc = DateTime::from_timestamp(seconds, 0).unwrap().naive_utc(); + tz.offset_from_utc_datetime(&utc).fix().local_minus_utc() + } + + #[test] + fn utc_offset_spans_find_transitions() { + let tz: Tz = "America/New_York".parse().unwrap(); + let spans = UtcOffsetSpans::new(&tz).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); + } + for tz in ["UTC", "+05:30"] { + let spans = UtcOffsetSpans::new(&tz.parse().unwrap()).unwrap(); + assert!(spans.transitions.is_empty(), "{tz}"); + assert_eq!( + spans.span(0), + UtcOffsetSpan { + start: i64::MIN, + end: i64::MAX, + offset: if tz == "UTC" { 0 } else { 19_800 }, + } + ); + } + } + + #[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() + ); + } + } + } + + /// 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::new(&tz).unwrap(); + let mut seconds = spans + .transitions + .iter() + .flat_map(|&transition| { + [-SECONDS_PER_DAY, -3600, -1, 0, 1, 3600, SECONDS_PER_DAY] + .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() { + let tz: Tz = "America/New_York".parse().unwrap(); + let spans = UtcOffsetSpans::new(&tz).unwrap(); + for granularity in [DatePart::Hour, DatePart::Day, DatePart::Year] { + // 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()), + ); + } + } + #[test] fn output_ordering_respects_timestamp_timezone() { let precision_value = ScalarValue::Utf8(Some("hour".into())); From 88919ae3bca17dfa647e2f8c6db77d92b5db3210 Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Wed, 2 Dec 2026 12:39:08 +0800 Subject: [PATCH 2/3] Skip the transition scan for UTC and fixed offsets `UTC` and fixed offsets such as `+05:30` have no transitions, so build their single span directly instead of scanning 1800 to 2200 for the offset changes and caching the result per timezone name. --- .../functions/src/datetime/date_trunc.rs | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/datafusion/functions/src/datetime/date_trunc.rs b/datafusion/functions/src/datetime/date_trunc.rs index 6578698d63c7b..106a54765f168 100644 --- a/datafusion/functions/src/datetime/date_trunc.rs +++ b/datafusion/functions/src/datetime/date_trunc.rs @@ -1419,6 +1419,12 @@ impl UtcOffsetSpans { /// [`UtcOffsetSpans`] of `tz`, computed once per timezone name. fn cached_utc_offset_spans(tz_name: &str, tz: Tz) -> Option> { + if let Some(offset) = constant_utc_offset(tz_name, &tz) { + return Some(Arc::new(UtcOffsetSpans { + transitions: vec![], + offsets: vec![offset], + })); + } static CACHE: LazyLock>>>> = LazyLock::new(Default::default); let lock = || CACHE.lock().unwrap_or_else(PoisonError::into_inner); @@ -1430,6 +1436,17 @@ fn cached_utc_offset_spans(tz_name: &str, tz: Tz) -> Option> lock().entry(tz_name.to_owned()).or_insert(spans).clone() } +/// The UTC offset of `tz` if `tz` is `UTC` or a fixed offset such as `+05:30`, +/// which have no transitions to scan for. Arrow parses a name that starts with +/// `+` or `-` as a fixed offset, and no tz database name starts with either. +fn constant_utc_offset(tz_name: &str, tz: &Tz) -> Option { + (is_utc(tz_name) || tz_name.starts_with(['+', '-'])).then(|| { + tz.offset_from_utc_datetime(&DateTime::UNIX_EPOCH.naive_utc()) + .fix() + .local_minus_utc() + }) +} + /// 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; @@ -1537,8 +1554,8 @@ mod tests { use crate::datetime::date_trunc::{ DateTruncFunc, NANOS_PER_MICROSECOND, NANOS_PER_SECOND, SECONDS_PER_DAY, TRANSITION_SCAN_END, TRANSITION_SCAN_START, UtcOffsetSpan, UtcOffsetSpans, - date_trunc_coarse, date_trunc_coarse_with_spans, general_date_trunc, - general_date_trunc_array_fine_granularity, parse_granularity, + constant_utc_offset, date_trunc_coarse, date_trunc_coarse_with_spans, + general_date_trunc, general_date_trunc_array_fine_granularity, parse_granularity, }; use arrow::array::cast::as_primitive_array; @@ -1596,6 +1613,27 @@ mod tests { } } + #[test] + fn constant_utc_offset_matches_transition_scan() { + for (name, expected) in [ + ("UTC", Some(0)), + ("+00:00", Some(0)), + ("+05:30", Some(19_800)), + ("-0930", Some(-34_200)), + ("+14", Some(50_400)), + ("Etc/GMT+5", None), + ("America/New_York", None), + ] { + let tz: Tz = name.parse().unwrap(); + assert_eq!(constant_utc_offset(name, &tz), expected, "{name}"); + if let Some(offset) = expected { + let spans = UtcOffsetSpans::new(&tz).unwrap(); + assert!(spans.transitions.is_empty(), "{name}"); + assert_eq!(spans.offsets, [offset], "{name}"); + } + } + } + #[test] fn timezone_offsets_are_constant_outside_transition_scan_window() { const HALF_YEAR: i64 = 183 * SECONDS_PER_DAY; From f9598fb140ac0a926723f1340c56f1a1d8835d44 Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Wed, 2 Dec 2026 12:56:22 +0800 Subject: [PATCH 3/3] Move the UTC offset spans to `datafusion_common::timezone` The per-timezone transition table and its cache now live in `datafusion-common`, so other timezone code can share it instead of keeping its own global. The module is hidden from the docs and is for internal use only. The spans are stored as boxed slices, which drops the vectors' spare capacity (New York: 6,144 to 4,312 bytes). Names that fail to parse are not cached, so the cache holds at most one entry per tz database name. --- Cargo.lock | 1 + datafusion/common/Cargo.toml | 1 + datafusion/common/src/lib.rs | 2 + datafusion/common/src/timezone.rs | 224 +++++++++++++++++ .../functions/src/datetime/date_trunc.rs | 228 ++---------------- 5 files changed, 247 insertions(+), 209 deletions(-) create mode 100644 datafusion/common/src/timezone.rs diff --git a/Cargo.lock b/Cargo.lock index d9da77fa4b988..2bdb717006303 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1922,6 +1922,7 @@ dependencies = [ "arrow-schema", "arrow-select", "chrono", + "chrono-tz", "criterion", "foldhash 0.2.0", "half", diff --git a/datafusion/common/Cargo.toml b/datafusion/common/Cargo.toml index 998ffa90c9f72..fd956ea52786d 100644 --- a/datafusion/common/Cargo.toml +++ b/datafusion/common/Cargo.toml @@ -82,6 +82,7 @@ web-time = "1.1.0" [dev-dependencies] chrono = { workspace = true } +chrono-tz = "0.10.4" criterion = { workspace = true } insta = { workspace = true } rand = { workspace = true } diff --git a/datafusion/common/src/lib.rs b/datafusion/common/src/lib.rs index b37ee729c9e63..839a523056172 100644 --- a/datafusion/common/src/lib.rs +++ b/datafusion/common/src/lib.rs @@ -49,6 +49,8 @@ pub mod scalar; pub mod spans; pub mod stats; pub mod test_util; +#[doc(hidden)] +pub mod timezone; pub mod tree_node; pub mod types; pub mod utils; diff --git a/datafusion/common/src/timezone.rs b/datafusion/common/src/timezone.rs new file mode 100644 index 0000000000000..b37d8a348ea89 --- /dev/null +++ b/datafusion/common/src/timezone.rs @@ -0,0 +1,224 @@ +// 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. +//! +//! # Public Only for Internal Use: +//! +//! This is not a public API and is for internal use only; see [API policy] for details. +//! +//! [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis + +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. +/// +/// ``` +/// use datafusion_common::timezone::UtcOffsetSpans; +/// +/// let spans = UtcOffsetSpans::for_timezone("America/New_York").unwrap(); +/// // New York moved from UTC-5 to UTC-4 at 2024-03-10T07:00:00Z. +/// assert_eq!(spans.span(1_710_053_999).offset, -5 * 3600); +/// assert_eq!(spans.span(1_710_054_000).offset, -4 * 3600); +/// assert_eq!(spans.span(1_710_054_000).start, 1_710_054_000); +/// ``` +#[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. + 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() + ); + } + } + } +} diff --git a/datafusion/functions/src/datetime/date_trunc.rs b/datafusion/functions/src/datetime/date_trunc.rs index 106a54765f168..df0355bbdfab3 100644 --- a/datafusion/functions/src/datetime/date_trunc.rs +++ b/datafusion/functions/src/datetime/date_trunc.rs @@ -3,11 +3,10 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements use std::cell::Cell; -use std::collections::HashMap; use std::num::NonZeroI64; use std::ops::{Add, Sub}; use std::str::FromStr; -use std::sync::{Arc, LazyLock, Mutex, PoisonError}; +use std::sync::Arc; use crate::datetime::common::parse_tz; use arrow::array::temporal_conversions::{ @@ -26,6 +25,7 @@ use arrow::datatypes::DataType::{self, Date32, Date64, Time32, Time64, Timestamp use arrow::datatypes::TimeUnit::{self, Microsecond, Millisecond, Nanosecond, Second}; use arrow::datatypes::{Field, FieldRef}; use datafusion_common::cast::as_primitive_array; +use datafusion_common::timezone::{UtcOffsetSpan, UtcOffsetSpans}; use datafusion_common::types::{NativeType, logical_date, logical_string}; use datafusion_common::utils::take_function_args; use datafusion_common::{ @@ -43,7 +43,7 @@ use datafusion_macros::user_doc; use chrono::{ DateTime, Datelike, Duration, LocalResult, Months, NaiveDate, NaiveDateTime, Offset, - TimeDelta, TimeZone, Timelike, Weekday, + TimeDelta, Timelike, Weekday, }; fn parse_granularity(value: &str) -> Result { @@ -293,7 +293,7 @@ impl ScalarUDFImpl for DateTruncFunc { } if let (Some(tz_name), Some(tz)) = (tz_opt, parsed_tz) - && let Some(spans) = cached_utc_offset_spans(tz_name, 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()); @@ -1295,8 +1295,13 @@ fn date_trunc_coarse_with_spans( Microsecond => NANOS_PER_MICROSECOND, Nanosecond => 1, }; - // Sorted input stays in one span for long runs, so look it up only on a change. - let span = Cell::new(UtcOffsetSpan::EMPTY); + // 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 { @@ -1336,123 +1341,6 @@ fn date_trunc_coarse_with_spans( }) } -/// 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)] -struct UtcOffsetSpans { - transitions: Vec, - offsets: Vec, -} - -/// The epoch seconds `[start, end)` over which a timezone has `offset`. -#[derive(Clone, Copy, Debug, PartialEq)] -struct UtcOffsetSpan { - start: i64, - end: i64, - offset: i32, -} - -impl UtcOffsetSpan { - const EMPTY: Self = Self { - start: i64::MAX, - end: i64::MIN, - offset: 0, - }; - - fn contains(&self, seconds: i64) -> bool { - self.start <= seconds && seconds < self.end - } -} - -impl UtcOffsetSpans { - /// 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 new(tz: &Tz) -> Option { - let offset_at = |seconds: i64| { - let utc = DateTime::from_timestamp(seconds, 0)?.naive_utc(); - Some(tz.offset_from_utc_datetime(&utc).fix().local_minus_utc()) - }; - let mut transitions = vec![]; - let mut offsets = vec![offset_at(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(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(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(after)?; - transitions.push(after); - offsets.push(offset); - day = after; - } - Some(Self { - transitions, - offsets, - }) - } - - /// The span that contains `seconds`. - 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], - } - } -} - -/// [`UtcOffsetSpans`] of `tz`, computed once per timezone name. -fn cached_utc_offset_spans(tz_name: &str, tz: Tz) -> Option> { - if let Some(offset) = constant_utc_offset(tz_name, &tz) { - return Some(Arc::new(UtcOffsetSpans { - transitions: vec![], - offsets: vec![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_name) { - return spans.clone(); - } - // Scan without holding the lock, which takes milliseconds. - let spans = UtcOffsetSpans::new(&tz).map(Arc::new); - lock().entry(tz_name.to_owned()).or_insert(spans).clone() -} - -/// The UTC offset of `tz` if `tz` is `UTC` or a fixed offset such as `+05:30`, -/// which have no transitions to scan for. Arrow parses a name that starts with -/// `+` or `-` as a fixed offset, and no tz database name starts with either. -fn constant_utc_offset(tz_name: &str, tz: &Tz) -> Option { - (is_utc(tz_name) || tz_name.starts_with(['+', '-'])).then(|| { - tz.offset_from_utc_datetime(&DateTime::UNIX_EPOCH.naive_utc()) - .fix() - .local_minus_utc() - }) -} - -/// 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 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 { @@ -1552,10 +1440,9 @@ mod tests { use std::sync::Arc; use crate::datetime::date_trunc::{ - DateTruncFunc, NANOS_PER_MICROSECOND, NANOS_PER_SECOND, SECONDS_PER_DAY, - TRANSITION_SCAN_END, TRANSITION_SCAN_START, UtcOffsetSpan, UtcOffsetSpans, - constant_utc_offset, date_trunc_coarse, date_trunc_coarse_with_spans, - general_date_trunc, general_date_trunc_array_fine_granularity, parse_granularity, + 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 arrow::array::cast::as_primitive_array; @@ -1574,88 +1461,11 @@ mod tests { use arrow::datatypes::{DataType, Field, TimeUnit}; use datafusion_common::ScalarValue; use datafusion_common::config::ConfigOptions; + use datafusion_common::timezone::UtcOffsetSpans; use datafusion_expr::interval_arithmetic::Interval; use datafusion_expr::sort_properties::{ExprProperties, SortProperties}; use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl}; - use chrono::{DateTime, Offset, TimeZone}; - - fn offset_at(tz: &Tz, seconds: i64) -> i32 { - let utc = DateTime::from_timestamp(seconds, 0).unwrap().naive_utc(); - tz.offset_from_utc_datetime(&utc).fix().local_minus_utc() - } - - #[test] - fn utc_offset_spans_find_transitions() { - let tz: Tz = "America/New_York".parse().unwrap(); - let spans = UtcOffsetSpans::new(&tz).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); - } - for tz in ["UTC", "+05:30"] { - let spans = UtcOffsetSpans::new(&tz.parse().unwrap()).unwrap(); - assert!(spans.transitions.is_empty(), "{tz}"); - assert_eq!( - spans.span(0), - UtcOffsetSpan { - start: i64::MIN, - end: i64::MAX, - offset: if tz == "UTC" { 0 } else { 19_800 }, - } - ); - } - } - - #[test] - fn constant_utc_offset_matches_transition_scan() { - for (name, expected) in [ - ("UTC", Some(0)), - ("+00:00", Some(0)), - ("+05:30", Some(19_800)), - ("-0930", Some(-34_200)), - ("+14", Some(50_400)), - ("Etc/GMT+5", None), - ("America/New_York", None), - ] { - let tz: Tz = name.parse().unwrap(); - assert_eq!(constant_utc_offset(name, &tz), expected, "{name}"); - if let Some(offset) = expected { - let spans = UtcOffsetSpans::new(&tz).unwrap(); - assert!(spans.transitions.is_empty(), "{name}"); - assert_eq!(spans.offsets, [offset], "{name}"); - } - } - } - - #[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() - ); - } - } - } - /// 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 @@ -1737,12 +1547,12 @@ mod tests { "Pacific/Kiritimati", ] { let tz: Tz = zone.parse().unwrap(); - let spans = UtcOffsetSpans::new(&tz).unwrap(); + let spans = UtcOffsetSpans::for_timezone(zone).unwrap(); let mut seconds = spans - .transitions + .transitions() .iter() .flat_map(|&transition| { - [-SECONDS_PER_DAY, -3600, -1, 0, 1, 3600, SECONDS_PER_DAY] + [-86_400, -3600, -1, 0, 1, 3600, 86_400] .map(|delta| transition + delta) }) .chain([-1, 0, 1_700_000_000]) @@ -1761,7 +1571,7 @@ mod tests { #[test] fn date_trunc_with_spans_reports_out_of_range_like_chrono_path() { let tz: Tz = "America/New_York".parse().unwrap(); - let spans = UtcOffsetSpans::new(&tz).unwrap(); + let spans = UtcOffsetSpans::for_timezone("America/New_York").unwrap(); for granularity in [DatePart::Hour, DatePart::Day, DatePart::Year] { // Beyond the nanosecond range, and truncated below it. for value in [i64::MAX / 2, i64::MIN / 1_000_000_000] {