Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions datafusion/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ web-time = "1.1.0"

[dev-dependencies]
chrono = { workspace = true }
chrono-tz = "0.10.4"

Copy link
Copy Markdown
Contributor

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 chrono feels like going in the wrong direction.

Copy link
Copy Markdown
Contributor

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

criterion = { workspace = true }
insta = { workspace = true }
rand = { workspace = true }
Expand Down
2 changes: 2 additions & 0 deletions datafusion/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ pub mod scalar;
pub mod spans;
pub mod stats;
pub mod test_util;
#[doc(hidden)]
pub mod timezone;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small question: only date_trunc uses this so far. Is it in datafusion-common so #27732 can reuse it for the ordering check? If not, it could live next to date_trunc in datafusion-functions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. The API policy reserves #[doc(hidden)] pub for items shared across crates, and both users are in datafusion-functions: this file, and #27732, which still has its own utc_offset_transitions and cache in the same file. A pub(crate) module such as datafusion/functions/src/datetime/timezone.rs keeps it out of datafusion-common's API and drops the new chrono-tz dev-dependency there.

pub mod tree_node;
pub mod types;
pub mod utils;
Expand Down
224 changes: 224 additions & 0 deletions datafusion/common/src/timezone.rs
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> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like a labour intensive way to find the transitions. jiff::tz::TimeZone::following() would just tell you them.

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()
);
}
}
}
}
27 changes: 27 additions & 0 deletions datafusion/functions/benches/datetime_expressions/date_trunc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Loading