jayzhan211 commented on code in PR #27883:
URL: https://github.com/apache/datafusion/pull/27883#discussion_r4770085790
##########
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;
Review Comment:
+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.
##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -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<T: ArrowTimestampType>(
+ array: &PrimitiveArray<T>,
+ granularity: DatePart,
+ tz: Tz,
+ spans: &UtcOffsetSpans,
+) -> Result<PrimitiveArray<T>> {
+ 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 =>
Review Comment:
Removing `offset == current.offset` from this match still passes every test
in the PR, but it returns wrong results. In America/Creston, `year` on
`[1944-08-18T19:39:14Z, 1944-11-08T00:10:20Z]` gives 1944-01-01T06:00Z twice
instead of 06:00Z and 07:00Z. Creston fell back at 00:01 on 1944-01-01, so that
midnight happened twice, and the chrono path picks the instant with the input's
offset. Could you add this test so the offset stays in the key?
```rs
/// 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::<TimestampSecondType>::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]);
}
```
##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -1380,10 +1461,149 @@ 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};
+ /// 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<T: ArrowTimestampType>(
+ 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::<Vec<_>>();
+ 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::<T>::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::<Vec<_>>();
+ seconds.sort_unstable();
+ seconds.dedup();
+ check::<TimestampSecondType>(zone, tz, &spans, &seconds);
+ let nanos = seconds
+ .iter()
+ .map(|&seconds| seconds * NANOS_PER_SECOND + 123_456_789)
+ .collect::<Vec<_>>();
+ check::<TimestampNanosecondType>(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::for_timezone("America/New_York").unwrap();
+ for granularity in [DatePart::Hour, DatePart::Day, DatePart::Year] {
Review Comment:
Optional: this test still passes if the truncation fallback in the kernel
returns `Some(0)` instead of taking the chrono path. Near `i64::MIN`, New
York's negative offset already overflows in `checked_add`, so the truncation's
own overflow is never reached. Adding a zone east of UTC covers it:
```suggestion
// Near `i64::MIN`, adding a west offset overflows, while an east
zone
// reaches the truncation and overflows there.
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();
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]