Repository navigation
perf: truncate timezone-aware timestamps with integer arithmetic in date_trunc
#27883
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -49,6 +49,8 @@ pub mod scalar; | |
| pub mod spans; | ||
| pub mod stats; | ||
| pub mod test_util; | ||
| #[doc(hidden)] | ||
| pub mod timezone; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Small question: only
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. +1. The API policy reserves |
||
| pub mod tree_node; | ||
| pub mod types; | ||
| pub mod utils; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<Arc<Self>> { | ||
| // 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<Mutex<HashMap<String, Option<Arc<UtcOffsetSpans>>>>> = | ||
| 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<Self> { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This seems like a labour intensive way to find the transitions. |
||
| 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<i32> { | ||
| 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() | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since RUSTSEC-2026-0543 having more dependency on
chronofeels like going in the wrong direction.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We might need to deprecate and intro jiff in arrow-rs as the first step